Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop co-routine?

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");
        }
}
like image 595
Sudhir Kotila Avatar asked Aug 08 '14 12:08

Sudhir Kotila


People also ask

Do you need to stop coroutine?

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.

Can you pause a coroutine?

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 .

How do you stop a coroutine within the coroutine Unity?

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.

How do I turn off IEnumerator?

You can stop it if you start it with a string parameter like this : StartCoroutine( "DoAction" ); StopCoroutine( "DoAction" );


1 Answers

There are three ways to stop coroutines.

  1. The first is to call StopAllCoroutines(), which will obviously stop all running coroutines.
  2. The second is to call StopCoroutine(coroutine), where coroutine is a variable name given to your IEnumerator.
  3. And the third is to do a 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.

like image 160
Imapler Avatar answered Sep 24 '22 19:09

Imapler