Coroutines in Unity

Sean Kaleomaikalani Ferreira
2 min readSep 27, 2023

--

Coroutine, that’s such a strange word written out, but it’s not that complicated of a thought. In this context, it’s just a code execution that is happening along side the mainline execution.

One of many new functions we’ll be learning today

Coroutines in Unity have some strange terminology involved in them that we need to remember in order to use them, but first we’ll start with a new function: StartCoroutine();

This function starts the whole chain off, and it’s where you put the name of your coroutine function, along with any parameters it may need

IEnumerator is a new term for many and it occupies the return value of a function. IEnumerator is used for all coroutines, as they have a unique return phrase.

yield return new WaitForSeconds() is a term required to even run the coroutine. It is basically a time check and waits a designated amount of time before executing anything. In the image above, WaitForSeconds() has a float variable of “wait” in there, it’s the parameter given to the coroutine when it starts, it’s not necessary, as you can just put in a float value (like 5.0f), but it’s cleaner.

Infinite Coroutine

Now that’s great an all, but without any special code, the coroutine would just wait out a timer and end. Now with an infinite while loop, you’ve made an infinite coroutine! It doesn’t do anything, but it never turns off!

In my most recent project, I used a coroutine to have infinitely spawning enemies, but they’d spawn at random time intervals and random locations. The while loop in this coroutine is controlled by an external boolean, which would turn to false if the player died (aka: GAME OVER).

I hope this helps you better understand the basics of coroutines so you can use them in your coding journey!

--

--