Coroutines In Unity3D – The Gritty Details

In my last post I talked about why some code is easier to write, read and maintain in Unity 3D when it’s written using coroutines, and touched on how Unity3D uses C# iterators to implement them. Now let’s look at how Unity3D makes these work as coroutines.

With iterators your code is responsible for creating an iterator and causing the iterator code to continue after a yield statement, such as using foreach in the MSDN example. In Unity’s world coroutines work if you are a class derived from MonoBehaviour. This class has a function StartCoroutine() which can start any function which returns IEnumerator as a coroutine.

Coroutines aren’t very useful until they include a yield statement. Unity uses the values returned by yield as scheduling information – to decide when to call the next portion of the coroutine. I’ve never found a complete list of acceptable return values from yield for Unity3D. Here’s the ones I know about:

It’s not multithreading!

There’s no multi-threading going on here. All scripts in Unity are called on a single thread, so no locking of variables is required. However other scripts may change global or object state between function calls or across a yield instruction. At times it becomes important to know when during a frame the coroutine will be executed. The overall execution order documentation says:

  • Most coroutines run after Update() and before LateUpdate()
  • Coroutines started from LateUpdate() run after LateUpdate()
  • return yield new WaitForFixedUpdate() // causes a coroutine to run after the next FixedUpdate()

As a final complication StartCoroutine() causes the coroutine to run immediately, until its first yield.

That All Sounds Hard

It’s not. I’ve dug in here, and documented all the gritty details. 90% of the time you don’t need these details at all. Looking at my coroutines they are almost all using

  • yield break;
  • yield return null;
  • yield return StartCoroutine().

What are you waiting for? If it sounds like coroutines will solve a problem for you – try them out!

Advertisement

C# Coroutines In Unity3D

Why?

It seems like the best way to explain coroutines is by example. We’ll look at a portion of the class which controls the front-end in a game, and doesn’t use coroutines. It’s not horrible, but the logic is scattered across a delegate – OnPlayButton() and UpdateFrame(). We need a class member to hold a reference to the active UI page.

public class Frontend: GameState
{
    // need a member variable to hold a reference between functions
    private ZoneSelectUIPage mZoneSelectUIPage;

    public void Create()
    {
        mPlayButton = UITextButton.Create(GlobalResources.Instance.ButtonToolkit,
                                          "blank_up.png", "blank_down.png", font,
                                          fontMat, fontDropShadowMat, fontHighlightMat);
        mPlayButton.SetText("Play");
        mPlayButton.pixelsFromTopLeft(20, 20);

        // add delegate to handle button presses
        mPlayButton.AddOnTouchUpInside(OnPlayButton);
        ...
    }

    private void OnPlayButton(UIButton sender)
    {
        Hide();

        mZoneSelectUIPage = ZoneSelectUIPage.create();
        mZoneSelectUIPage.Show();
    }

    // called once a frame - that's how the game engine works!
    public GameState UpdateFrame()
    {
        if (mZoneSelectUIPage != null)
        {
            if (mZoneSelectUIPage.Level >= 0)
            {
                GlobalResources.Instance.SetLevel(mZoneSelectUIPage.Zone,
                                                  mZoneSelectUIPage.Level);
                mNextState = LevelLoadState.Instance;
            }

            if (mZoneSelectUIPage.Done)
            {
                mZoneSelectUIPage.Destroy();
                mZoneSelectUIPage = null;

                Show();
            }
        }

        return mNextState;
    }
}

On top of that there’s also a bunch of code to test whether mZoneSelectUIPage is null – we may not have one! The page also needs to explicitly contain a property ZoneSelectUIPage.Done which we can test to see if it’s work is done. Re-writing that using coroutines moves the logic into a single function CoroutineUpdate() and makes the logic linear to read.

public class Frontend: MonoBehaviour, GameState
{
    public void Create()
    {
        mPlayButton = UITextButton.Create(GlobalResources.Instance.ButtonToolkit,
                                          "blank_up.png", "blank_down.png", font,
                                          fontMat, fontDropShadowMat, fontHighlightMat);
        mPlayButton.SetText("Play");
        mPlayButton.pixelsFromTopLeft(20, 20);

        // now we start a coroutine to do our work
        StartCoroutine(CoroutineUpdate());
        ...
    }

    // called once a frame - that's how the game engine works!
    // bridge to the engine by having the coroutine set mNextState
    public GameState UpdateFrame()
    {
        return mNextState;
    }

    public IEnumerator CoroutineUpdate()
    {
        while (true)
        {
            // wait until the next frame update
            yield return null;

            if (mPlayButton.TouchUp)
            {
                Hide();

                ZoneSelectUIPage zoneSelectUIPage = ZoneSelectUIPage.create();

                yield return StartCoroutine(zoneSelectUIPage.CoroutineUpdate());

                if (zoneSelectUIPage.Level >= 0)
                {
                    GlobalResources.Instance.SetLevel(zoneSelectUIPage.Zone,
                                                      zoneSelectUIPage.Level);
                    mNextState = LevelLoadState.Instance;
                }

                zoneSelectUIPage.Destroy();

                // exit the coroutine
                yield break;
            }
        }
    }
}

Also we no longer have to check whether zoneSelectUIPage is null – it’s a local variable we’ve just created – or whether it’s finished. Once ZoneSelectUIPage.CoroutineUpdate() returns it’s done.

For this simple example the code is neater and simpler. As more buttons and pages are added the more of a win using coroutines is. Often game classes will end up with a state enumeration and state member variable, and the UpdateFrame() function becomes a gigantic switch statement. Each state may need additional variables, which become member variables. Over time it becomes hard to follow the logic and remember which variables affect which state. I’ve always found code like this to be hard to write and harder to read. With coroutines the entire state machine is written in a linear fashion with local variables and yield statements. There’s a more direct mapping of the code written to its effect. That’s got to be a win!

C# Support

C#, of course, doesn’t really support coroutines. You’ve probably noticed that I’m using yield statements which are part of iterators. Iterators provide the language infrastructure to return a value from partway through a function (using yield), and then start executing the function again at a later time from just after the yield statement. Unity3D adds support for using iterators as coroutines, which I’ll cover in my next post.