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.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

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,380
    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,380
  5. herbie

    herbie

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