Search Unity

Exiting a coroutine

Discussion in 'Editor & General Support' started by sirival, Dec 1, 2011.

  1. sirival

    sirival

    Joined:
    Sep 14, 2011
    Posts:
    146
    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:

    Code (csharp):
    1.  
    2. void Start()
    3. {
    4.       StartCoroutine( Foo() );
    5. }
    6.  
    7. IEnumerator Foo()
    8. {
    9.     // do something
    10.     yield return new WaitForSeconds( 1 );
    11.  
    12.    // do something else
    13.    yield return new WaitForSeconds( 1 );
    14.  
    15.    if( errorHappened )
    16.    {
    17.          yield return 0;
    18.    }
    19.  
    20.    // error has not happened so move on
    21.    ...
    22.    // do something else
    23.    yield return new WaitForSeconds( 1 );
    24.  
    25.    // done
    26.    yield return 0;
    27. }
    28.  
    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
     
    ismaelnascimentoash likes this.
  2. tomvds

    tomvds

    Joined:
    Oct 10, 2008
    Posts:
    1,028
    You can use
    Code (csharp):
    1. yield break;
    to exit a coroutine.
     
    SZtamjan, drbn, xjjon and 51 others like this.
  3. sirival

    sirival

    Joined:
    Sep 14, 2011
    Posts:
    146
    oh that's right :S

    Thanks!
     
  4. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    "yield return 0" means "wait a frame", basically the same as yield return null, but slightly less efficient. You can just do "return".

    --Eric
     
  5. Kerihobo

    Kerihobo

    Joined:
    Jun 26, 2013
    Posts:
    65
    My coroutine wouldn't let me simply "return". "yield break" worked though. Is "return" on it's own really possible?
     
    Yleisnero likes this.
  6. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    If you use Unityscript, yes.

    --Eric
     
  7. yuliyF

    yuliyF

    Joined:
    Nov 15, 2012
    Posts:
    197
    If my coroutine doen't finish any "yield.." - is it error?
     
  8. jesusluvsyooh

    jesusluvsyooh

    Joined:
    Jan 10, 2012
    Posts:
    377
    Hi thanks, 2020 and this is still the working solution.
    Had me confused why return; was not allowed.
     
    linenum, Zaddo, Fangh and 8 others like this.