unity3d Coroutines Coroutines


Example

First it's essential to understand that, game engines (such as Unity) work on a "frame based" paradigm.

Code is executed during every frame.

That includes Unity's own code, and your code.

When thinking about frames, it's important to understand that there is absolutely no guarantee of when frames happen. They do not happen on a regular beat. The gaps between frames could be, for example, 0.02632 then 0.021167 then 0.029778, and so on. In the example they are all "about" 1/50th of a second, but they are all different. And at any time, you may get a frame that takes much longer, or shorter; and your code may be executed at any time at all within the frame.

Bearing that in mind, you may ask: how do you access these frames in your code, in Unity?

Quite simply, you use either the Update() call, or, you use a coroutine. (Indeed - they are exactly the same thing: they allow code to be run every frame.)

The purpose of a coroutine is that:

you can run some code, and then, "stop and wait" until some future frame.

You can wait until the next frame, you can wait for a number of frames, or you can wait for some approximate time in seconds in the future.

For example, you can wait for "about one second", meaning it will wait for about one second, and then put your code in some frame roughly one second from now. (And indeed, within that frame, the code could be run at any time, whatsoever.) To repeat: it will not be exactly one second. Accurate timing is meaningless in a game engine.

Inside a coroutine:

To wait one frame:

// do something
yield return null;  // wait until next frame
// do something

To wait three frames:

// do something
yield return null;  // wait until three frames from now
yield return null;
yield return null;
// do something

To wait approximately half a second:

// do something
yield return new WaitForSeconds (0.5f); // wait for a frame in about .5 seconds
// do something

Do something every single frame:

while (true)
{
    // do something
    yield return null;  // wait until the next frame
}

That example is literally identical to simply putting something inside Unity's "Update" call: the code at "do something" is run every frame.

Example

Attach Ticker to a GameObject. While that game object is active, the tick will run. Note that the script carefully stops the coroutine, when the game object becomes inactive; this is usually an important aspect of correctly engineering coroutine usage.

using UnityEngine;
using System.Collections;

public class Ticker:MonoBehaviour {

    void OnEnable()
    {
        StartCoroutine(TickEverySecond());
    }

    void OnDisable()
    {
        StopAllCoroutines();
    }

    IEnumerator TickEverySecond()
    {
        var wait = new WaitForSeconds(1f); // REMEMBER: IT IS ONLY APPROXIMATE
        while(true)
        {
            Debug.Log("Tick");
            yield return wait;  // wait for a frame, about 1 second from now
        }
    }
}