extrawurst's blog

unity coroutines at editor time

• unity and general

Did you ever try to do non-blocking WWW-requests in Unity without being in playmode ? Then you know about the problems here:

The solution is twofold:

Pseudocode says more than a thousand words:

IEnumerator coroutine;

void Init()
{
EditorApplication.update += EditorUpdate;

// StartRequest is build like a normal
// coroutine and yield returns on WWW
coroutine = StartRequest();
}

void EditorUpdate()
{
coroutine.MoveNext();
}

This does the trick and is not widely known unfortunately. Using EditorApplication.update we can register arbitrary callbacks that get called periodically in Editor-Mode.

Additionally understanding unity coroutines is necessary to understand what we are doing here: A coroutine is nothing but a resumable method that is identified by the return type IEnumerator and the usage of yield return xyz; in its body. Under the hood it works by ‘someone’ calling MoveNext of its IEnumerable interface. Usually this ‘someone’ is Unity internally. But since that does not happen outside the playmode we can force it to still do the same by calling it manually.

Final note: EditorApplication.timeSinceStartup is great for actual timing in the registered update-callback.

comments powered by Disqus