Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

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.
     
  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,341
    "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:
    56
    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,341
    If you use Unityscript, yes.

    --Eric
     
  7. yuliyF

    yuliyF

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

    jesusluvsyooh

    Joined:
    Jan 10, 2012
    Posts:
    369
    Hi thanks, 2020 and this is still the working solution.
    Had me confused why return; was not allowed.
     
unityunity