evaluation order of coroutines confusion.

I am new to the concept of yield and IEnumerator and am working through some misconceptions.

StartCoroutine almost allows you to pretend you are spawning a little subprocess but in fact something has to be continually calling the routine until it is finished. (and besides it is generally useful that calls happen once per frame)

I am imagining StartCoroutine does something like add an object to a list that is polled at certain well defined points defined by Unity: (1) After performing all updates for this frame, (2)After performing all FixedUpdates for one physics iteration, (3) After rendering. These correspond to returning 0, WaitForFixedUpdate(), WaitForEndOfFrame() respectively.

So in fact return 0 could be conceptually WaitForUpdate() if such a function existed.

Does this make sense or have I still not quite got it?

Another thing I was looking for was something like WaitForLateUpdate()… This would have been very useful to me for defining some procedural animation that can be started from anywhere. Without WaitForLateUpdate(), it seems like I must have a LateUpdate implemented even if the procedural animation only applys occasionally. (I was going to use it to animate the avatar to face the camera when the player has been idle for a certain period)

Another thing I am unclear on is when coroutines are stopped automatically. For example I am assuming the destruction of the object does this, so you do not always have to call stopAllCoroutines on all objects that might have coroutines in progress.

A coroutine stops if there’s no more code to run:

function Start () {
    MyRoutine();
}

function MyRoutine () {
    // Run for 10 seconds
    for (i = 0.0; i < 10.0; i += Time.deltaTime) {
        yield;
    }
    // Coroutine ends here
}

The docs say that coroutines are run after Update, however this isn’t 100% true. In the example above, the coroutine is being called from Start, and in fact will run before Update, at least for the first frame.

–Eric

Yes until it hits the first yield it just seems to run like a normal function.

I didnt actually see the documentation that said they ran after Update(), but that seems to be what happens when I use yield return 0; (in c#). More specifically the coroutine is paused until all objects have called Update() for that frame, as far as I could tell.

http://unity3d.com/support/documentation/Manual/Execution%20Order.html

–Eric

Thanks, it gives me a lot more confidence to see it in documentation. Good link. :slight_smile: