Coroutines let us go from just writing functions to creating complex sequences with delays and timings.
(Note: If you haven’t used coroutines before, here’s a video that nails it.)
The most immediate uses for coroutines are for things like timers and animation sequences.
Stuff like “Count to 3 and explode”.
1 2 3 4 5 6 7 8 9 |
IEnumerator ExplosionSequence() { for (int i = 0; i < 3; i++) { yield return new WaitForSeconds(1f); } Explode(); } |
And this is great. A coroutine is perfect here.
But we can take this further.
What if we wanted a loading sequence which did something like:
“Show the loading screen, prepare the next level and, when it’s ready, hide the loading screen.”
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
GameObject LoadingScreen; IEnumerator LoadingSequence() { LoadingScreen.SetActive(true); yield return StartCoroutine(PrepareLevel()); LoadingScreen.SetActive(false); } IEnumerator PrepareLevel() { // pretending that level prep takes 2 seconds yield return new WaitForSeconds(2f); } |
In this example, the loading screen will show and 2 seconds later, when the level is done loading, hide itself.
The magic here is that a coroutine can yield return another coroutine, which resumes the original function when it’s done. Well worth keeping in your programming toolbelt!
Word of caution: nesting 3+ yield return ‘s that wait for coroutines to finish can be a pain to skim through and understand, so use it only when it makes sense!