Tags

Conventional wisdom says that coroutines only run while your game is playing. If you want to use a coroutine in an editor script, you’re just out of luck. As it turns out, that’s not quite entirely true.

You can manually iterate the coroutine.

After all, each coroutine is represented by an enumerator, and enumerators can be advanced by calling their MoveNext() function.

Bear in mind that coroutines are often waiting for a reason (say, WWW loads), whether it’s a change in state, time, or some async operation. Sometimes, though, I find myself writing a coroutine that spreads work over multiple frames for the sole purpose of avoiding performance hiccups.

As an example, I once wrote a game that built each level randomly. During gameplay, the level is built by a coroutine that takes several frames. When testing level builds in the editor, I couldn’t wait for frames because the game wasn’t running.

Instead of writing the same function twice, I write one coroutine and provide two hooks: one waits politely for the coroutine to finish on its own, the other forces it to finish immediately.

Here’s a simplified example:

void RuntimeBuild() {
    StartCoroutine(Build());
}

void EditorBuild() {
    IEnumerator e = Build();
    while (e.MoveNext());
}

IEnumerator Build() {
    Debug.Log("Started build");

    for (int i=0; i<10; i++) {
        Debug.Log(i);
        yield return null; //wait one frame
    }

    Debug.Log("Build finished!");
}
Advertisements