When two co-routines are running, how do you stop the first co-routine?
GLOBALS.stableTime = 5;
IEnumerator StableWaittingTime ()
{
yield return new WaitForSeconds (1f);
if (GLOBALS.stableTime == 0) {
GameManager.instance.LevelFaildMethod ();
} else {
GameManager.instance.stableWaittingTime.text = GLOBALS.stableTime.ToString ();
GLOBALS.stableTime--;
StartCoroutine ("StableWaittingTime");
}
}
A coroutine is just like a method except that you can yield in it. (not counting the stopping and how you call it). So if you mentally take the yield out, just ask yourself, will this coroutine ever end by reaching the last line in it. If so, you don't need to stop it.
You can only pause a coroutine at its suspension point. The block of code between suspension points is executed atomically by the CoroutineDispatcher. CoroutineDispatcher is a required element of a CoroutineContext .
To stop a coroutine from "inside" the coroutine, you cannot simply "return" as you would to leave early from an ordinary function. Instead, you use yield break . You can also force all coroutines launched by the script to halt before finishing.
You can stop it if you start it with a string parameter like this : StartCoroutine( "DoAction" ); StopCoroutine( "DoAction" );
There are three ways to stop coroutines.
StopAllCoroutines()
, which will obviously stop all running coroutines.StopCoroutine(coroutine)
, where coroutine
is a variable name given to your IEnumerator
.yield break
from within the coroutine.Worth noting is that both StopAllCoroutines and StopCoroutine can only stop a coroutine when the coroutine reaches a yield return *
.
So if you have two coroutines with the same name and you want to stop the one you are executing in you do yield break
.
Interestingly, if you want to stop every other coroutine besides the one you are executing in, you call StopCoroutines()
from within that coroutine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With