It seems that you cannot stop a Coroutine from within itself in 3.4.1 - I’m not sure if this was always the case or not, but I don’t remember it working this way in the past for some reason. Not a big deal, but also does not seem to be mentioned in the documentation anywhere - which, if this is by design and not a bug, it should be.
using UnityEngine;
using System.Collections;
public class CoroutineTest : MonoBehaviour {
IEnumerator Start(){
StartCoroutine("TestRoutine");
yield return new WaitForSeconds(3);
StopCoroutine("TestRoutine");
}
IEnumerator TestRoutine(){
while (true){
Debug.Log("Executing Test Routine");
// This does nothing - TestRoutine continues getting called until the "Start" IEnumerator stops me
StopCoroutine("TestRoutine");
yield return null;
}
}
}
The stop does not work from within the coroutine itself.
I think it has always been like this, cause StopCoroutine is to allow external code to stop it.
From within the coroutine you just use yield break; to terminate the coroutine
The example I gave is just the simplest example I could find that caused the issue. Where I actually encountered it was in a situation where a Coroutine causes a chain of events to take place that should exit out of the Coroutine (the actual StopCoroutine(“TestRoutine”) being in a separate, non-coroutine function).
Once I realized what was causing the issue it was simple enough to just rewrite my system to take the break out into consideration from within the Coroutine itself instead of in an external function - was mostly just curious if this had always been the case or if it was new.
Anyway, very easy to take into consideration assuming you know it works that way - probably worth a mention in the documentation. For situations like the example it is obvious what the “fix” is, but if you have something three functions deeper that’s just being called from the Coroutine, it can be a bit difficult to figure out why exactly it’s not functioning as desired. Especially if you call that function from somewhere else as well - in which case it works sporadically.
If you don’t call it inside the function it should work.
But its important to realize that a coroutine is bound to the component and gameobject on which its started, that means that other classes can’t terminate it, they have to call it through this one