Skip to content

Instantly share code, notes, and snippets.

@oleyb
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oleyb/2a504387e06825ec7d1c to your computer and use it in GitHub Desktop.
Save oleyb/2a504387e06825ec7d1c to your computer and use it in GitHub Desktop.
Unity3D extension method for being able to call an array of async code blocks in sequence.
public delegate float SequenceFunc();
public static void RunAsyncSequence(this MonoBehaviour obj, params SequenceFunc[] callbacks)
{
if (callbacks.Length > 0) {
obj.StartCoroutine(ExecFuncChain(callbacks));
}
}
private static IEnumerator ExecFuncChain(SequenceFunc[] callbacks)
{
// exec all but the last
for (int i = 0; i < callbacks.Length-1; ++i) {
yield return new WaitForSeconds(callbacks[i]());
}
// last is special case, just execute it and don't wait around
callbacks[callbacks.Length - 1]();
yield return new WaitForEndOfFrame();
}
// Usage:
this.RunAsyncSequence(
() => {
// Do async stuff and then call the next after 2 seconds
return 2;
},
() => {
// Do more stuff and then call the next after 3 seconds
return 3;
},
() => {
// Do final stuff
return 0;
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment