CoroutineScheduler

Author: Fernando Zapata (fernando@cpudreams.com) ported to CSharp by Frank Otto (http://fosion.de) Additional implementation for yield commands from the UnityEngine namespace by Gareth Williams (http://lonewolfwilliams.com)

Description
A simple coroutine scheduler. This coroutine scheduler allows for complete control over the execution regime of a set of coroutines. Reading the code will also help you understand how coroutines work behind the scenes. Understanding how coroutines are built on top of .Net generators will allow you to add coroutine support to a non-Unity project.

Coroutines can yield until the next update "yield;", until a given number of updates have passed "yield anInt;", until a given amount of seconds have passed "yield aFloat;", or until another coroutine has finished "yield scheduler.StartCoroutine(Coroutine);".

Multiple scheduler instances are supported and can be very useful. A coroutine running under one scheduler can yield (wait) for a coroutine running under a completely different scheduler instance.

Unity's YieldInstruction classes are not used because I cannot access their internal data needed for scheduling. Semantics are slightly different from Unity's scheduler. For example, in Unity if you start a coroutine it will run up to its first yield immediately, while in this scheduler it will not run until the next time UpdateAllCoroutines is called. This feature allows any code to start coroutines at any time, while making sure the started coroutines only run at specific times.

You should not depend on update order between coroutines running on the same update.

For a deeper understanding and to learn more about how coroutines are implemented as state machines by the compiler see the article quoted in this post.

Usage
Creating and driving CoroutineSchedulers is easy and is best shown by an example.

You normally would not use Unity's own Time.frameCount or Time.time as in that case you may as well use Unity's built-in scheduler, but it makes for an easy to understand example.

Starting coroutines and yielding execution is also best shown by an example.

For details on features not used in this particular example please read the doc comments. If you have any questions feel free to contact me directly at fernando@cpudreams.com.

CoroutineNode.js
Ported to CSharp

Additional Implementation C#
If you want to use CoroutineScheduler with Yield Commands from within the UnityEngine namespace here is an addition to the implementation, I found it useful for consuming api's in classes defined outside the UnityEngine namespace.

IYieldWrapper.cs
you will need to write your own implementations for yield commands from within the UnityEngine namespace, this interface should help facilitate that.

Example Wrappers
Below are some examples of wrappers I have used, in fact they have almost identical signatures so a more generic implementation could probably be written ^_^