- Home /
OnTrigger Stay/Exit - Stay Overriding Exit
Hi there, I am creating enemy AI by using a collider to see if player is in range. It appears that even though he exits, it has one more frame or something where he's still considered to be inside and as a result triggers OnTriggerStay one last time, stopping the Coroutine that needs to run, it should only stop the coroutine as long as someone is inside the trigger.
Code:
void OnTriggerStay(Collider collider)
{
StopCoroutine("loseTarget");
if(!isAggro)
{
locationWhenAggro = transform.position;
}
isAggro = true;
if(collider.tag == "Player" && !players.Contains(collider.gameObject))
{
players.Add(collider.gameObject);
}
}
void OnTriggerExit(Collider collider)
{
if(players.Contains(collider.gameObject))
{
players.Remove(collider.gameObject);
StartCoroutine("loseTarget");
}
}
IEnumerator loseTarget()
{
Debug.Log("Starting Count!");
yield return new WaitForSeconds(attentionTime);
Debug.Log("Count Over!");
if(players.Count == 0)
{
isAggro = false;
lastActionDecayTimer = lastActionDecayTime;
selectedTarget = null;
canChangeTarget = true;
}
}
Answer by torrmercury · Jan 26, 2014 at 07:06 PM
You should try using OnTriggerEnter for the StopCoroutine() function. Since StopCoroutine only needs to be called once, OnTriggerEnter would only call it once, rather than OnTriggerStay which would call it every frame while your character is inside of the trigger. Once your character exits, it would immediately start again because there is nothing telling it to stop anymore.
I'll mark it as correct because it solves the problem, but I'd still like to know why when I've technically exited the collider it still considers me as staying in the collider - I suppose both of those trigger on the same frame? Also you may want to remove your duplicate answer :)
Answer by torrmercury · Jan 26, 2014 at 06:17 PM
Try using OnTriggerEnter as the stop co-routine function. You only need to call it once and using enter is perfect for that because you only enter once. If you stay, funky stuff may happen with the colliders.