At the moment I’m having an issue with triggers only firing once. Basically, there’s a trigger that should disable a script (“ZombieFlee”) on another gameobject when said gameobject passes through the collider (OnTriggerStay2D).
This works great for one object! However, it only works… for one object. Even as I introduce more of the same object (prefabs), OnTriggerStay2D seems to fire only once and the rest of the objects continue to have ZombieFlee enabled. As far as I can tell, there’s nothing that should differentiate one prefab from another (they’re all tagged “Zombies”)… I’ve also tried OnTriggerExit2D, to no avail.
I’m a novice when it comes to C#, so I’m not quite sure what to do about this. Any and all help is appreciated! Thanks in advance!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DisableZombieFlee : MonoBehaviour
{
public float waitSeconds;
private bool isTriggered = false;
IEnumerator OnTriggerStay2D(Collider2D collision)
{
if (isTriggered == false)
{
yield return new WaitForSeconds(waitSeconds);
GameObject varGameObject = GameObject.FindWithTag("Zombie");
varGameObject.GetComponent<ZombieFlee>().enabled = false;
}
isTriggered = true;
}
void OnTriggerExit(Collider collision)
{
isTriggered = false;
}
}
If you haven’t fixed this yet, I think the error lies with using OnTriggerStay2D as a Coroutine. I’ve never tried using it as one, so I wouldn’t know. Anyway, try this out and let me know!
But, from what I’m guessing when you’re trying to find the GameObject with tag of “Zombie”, it’s finding the zombie that had already activated the trigger. I might be talking out of my butt right now but that’s what I’m jumping to base on an assumption.
Which if I’m correct, then what I would do is, as soon as that object leaves the trigger, set it’s tag to be something else like “alreadyFleeing” or something to that effect, or use a array to assign multiple objects that trigger it to it.
So, I’ve tried your version of the code, which worked fine on the one zombie! I tried the tag thing out as well, and for some reason, that doesn’t seem to be working… I probably wrote the code incorrectly, or it’s in the wrong place in my code, but here’s the section anyway:
I don’t get on here much and without seeing what you’re actually trying to do I don’t think I’ll be much help. However, if you want to add me on Discord and share screen I’m sure I might be able to help. But I’ll give it a shot…
I’m thinking that there isn’t anything that is detecting that the zombie has left the collider. Make sure you have your box ticked as “isTrigger”. If it is then try using collision.gameObject.tag == “Zombie”; since what I’m assuming is, it isn’t detecting it as a collision from that gameObject.