Search Unity

I'm a little confused about coroutines

Discussion in 'Scripting' started by herbie, May 2, 2017.

  1. herbie

    herbie

    Joined:
    Feb 11, 2012
    Posts:
    237
    Hi,

    I'm a little confused about coroutines.
    See the code below.

    Code (CSharp):
    1. IEnumerator f()
    2. {
    3.     yield return StartCoroutine(g());
    4.    
    5.     if (one == true)
    6.     {
    7.         Do something ....
    8.     }
    9. }
    10.  
    11. IEnumerator g()
    12. {
    13.     if (two == true)
    14.     {
    15.         Do something ....
    16.     }
    17.     if (three == true)
    18.     {
    19.         Do something ....
    20.     }
    21.    
    22.     yield return null;
    23. }
    Is it right that if-statement "two" is executed first, then if-statement "three" and then if-statement "one"?
    Are the if-statements "two" and "three" both finished before "yield return null" goes back to IEnumerator f()?
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,532
    if you start coroutine with 'f()', then the first thing that happens is we start coroutine g() and wait for it to complete

    while g is running, 'two' and 'three' are processed, THEN we yield null and wait one frame

    now g is complete so we return to f, and we run 'one'
     
  3. herbie

    herbie

    Joined:
    Feb 11, 2012
    Posts:
    237
    Ok thanks.
    So it's for sure that "three" is finished before we return to f and run "one"?
     
  4. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,532
  5. herbie

    herbie

    Joined:
    Feb 11, 2012
    Posts:
    237
    Thanks!
    It's all clear now.