Search Unity

Coroutines, Yield and functions other than WaitForSeconds in c#

Discussion in 'Scripting' started by tre4bax, Mar 1, 2015.

  1. tre4bax

    tre4bax

    Joined:
    Aug 31, 2013
    Posts:
    22
    Hi there,

    I have put together how to use coroutines and yield etc. quite happily but what I'm interested in is what causes WaitForSeconds to work?

    Does the function coming back with a specific value cause the yield to hold? I ask because I would like to implement something that steps through various points but only on sequential completion of something before it. With WaitForSeconds it can do

    <Action 1> wait <Action 2> wait etc.

    but what if I want to do

    <Action 1> <Wait for action 1 to complete> <action 2> <Wait for action 2 to complete> ...

    Seemed to me if I can implement a custom function called by yield this would work.

    I've struggled to find documentation on this because this way of using yield is not really as inteded in C# I suspect as it was really only intended for providing enumerated types. Would really be grateful for any suggestions you may have.
     
  2. Ecocide

    Ecocide

    Joined:
    Aug 4, 2011
    Posts:
    293
    I don't exactly understand what you mean, but in order to achieve something like this:
    " <Action 1> <Wait for action 1 to complete> <action 2> <Wait for action 2 to complete> ... "

    You can perfectly use coroutines for something like this:

    Code (csharp):
    1.  
    2. private IEnumerator Controller()
    3. {
    4.      yield return StartCoroutine(Action1());
    5.  
    6.      Debug.Log("Action1 finished");
    7.  
    8.      yield return StartCoroutine(Action2());
    9. }
    10.  
    11. private IEnumerator Action1()
    12. {
    13.      // do some work
    14.      yield return null;
    15.      // do some work... etc.
    16. }
    17.  
    18. private IEnumerator Action2()
    19. {
    20.      // do some work
    21.      yield return null;
    22.      // do some work... etc.
    23. }
    24.  
    The Debug.log statement will be called after the Action1 coroutine finished.
     
  3. tre4bax

    tre4bax

    Joined:
    Aug 31, 2013
    Posts:
    22
    Really useful ta. This has the germ of what I think I need to do which is to call a Coroutine that loops until my condition is set but uses WaitForSecond to ensure that it does not hog processing power. Having fun finding out anyway and that's really why I do this ;-)