How to use Coroutines in Unity

Create a coroutine to spawn an enemy every X seconds

A Coroutine is a function that can pause and wait while the rest of the code continues to run. Then after the wait it can continue the coroutine right where it waited.

IEnumerator type function is used to create an Coroutine in Unity. This allows us to use ‘yield’ which is used to tell Unity to wait. You always need to have a yield within IEnumerator.

Code Example — Coroutine

We want our script to spawn an enemy every 3 seconds.

To start the coroutine use StartCoroutine and state the name just like evry other function.

//wait for 3 seconds in float
yield return new WaitForSeconds(3f);

The yield part is what makes the IEnumerator function different. In our example it will wait for 3 seconds then continue to run the code from there again. For us it means it return to the top of the while loop again.

Spawn a enemy every 0.5s

Unity Scripting API Reference for Coroutine



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store