Exiting a coroutine

Hello,

I am running a coroutine and I want it to exit early if an error happens. However it doesn’t seem to work… Here is an example:

void Start()
{
      StartCoroutine( Foo() );
}

IEnumerator Foo()
{
    // do something
    yield return new WaitForSeconds( 1 );

   // do something else
   yield return new WaitForSeconds( 1 );

   if( errorHappened )
   {
         yield return 0;
   }

   // error has not happened so move on
   ...
   // do something else
   yield return new WaitForSeconds( 1 );

   // done
   yield return 0;
}

In this example when errorHappened is true the coroutine will yield and then continue its execution as if nothing happened…

Does this mean that the only way to exit a coroutine early is to call StopCoroutine ?

Thank you

1 Like

You can use

yield break;

to exit a coroutine.

55 Likes

oh that’s right :S

Thanks!

“yield return 0” means “wait a frame”, basically the same as yield return null, but slightly less efficient. You can just do “return”.

–Eric

My coroutine wouldn’t let me simply “return”. “yield break” worked though. Is “return” on it’s own really possible?

1 Like

If you use Unityscript, yes.

–Eric

If my coroutine doen’t finish any “yield…” - is it error?

Hi thanks, 2020 and this is still the working solution.
Had me confused why return; was not allowed.

11 Likes