Later on, I figured out that StopAllCoroutines
is pretty evil, since it causes problems for any coroutine that may ever be played. I went for an approach where I stored the UnityEngine.Coroutine
handle of each coroutine to be kept track of as fields in EnemyAI.cs
, and stopped these coroutines one at a time using the override for StopCoroutine
which uses a Coroutine
as an argument.
private Coroutine patrolCoroutineHandle;
private Coroutine chaseCoroutineHandle;
private Coroutine attackCoroutineHandle;
Whenever a state changes, a method which looks like the one below is called.
private void StartPatrolling()
{
state = State.Patrolling;
if (chaseCoroutineHandle != null && attackCoroutineHandle != null)
{
StopCoroutine(chaseCoroutineHandle);
weaponSystem.StopCoroutine(attackCoroutineHandle);
}
patrolCoroutineHandle = StartCoroutine(Patrol());
}
The drawback to this is that one must remember which MonoBehaviour
class called a given coroutine, and stop the called coroutine through this class, otherwise Unity throws up a cryptic coroutine continue failure
error, which doesn’t otherwise halt gameplay.
Removing all StopAllCoroutines
calls allowed me to use coroutines normally. The idea sprang from Ben’s fix for the scene not reloading when the player was killed.