Last active
August 29, 2015 14:21
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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