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;
}
}