How To Use IEnumerator Coroutines In Unity!

Adam Reed
2 min readApr 1, 2021

--

A standard “void” method applies its functions all within a single frame. Coroutines allow the use of the “yield” function to suspend the method until either the next frame or a set amount of time goes by.

[IMPORTANT NOTE]

When using a coroutine you must make sure that you are using the “using System.Collections;” namespace.

This is an example of an “IEnumerator” coroutine utilizing a while loop with “yield return new WaitForSeconds()” embedded in it to spawn new enemies at a random location on the top of the screen every second.

This is an example of a “void” method that spawns new enemies at a random location on the top of the screen.

Notice that it’s spawning a ton of enemies all at once. If I had left it in the while loop instead of moving it into the void Update function, it would have crashed Unity and possibly my computer.

Here’s how to use the IEnumerator function to create coroutines!

By using “yield return null;” in your coroutine, you end the method until the next frame.

By using “yield return new WaitForSeconds(x);” in your coroutine, you can input a float value to set a specific number of seconds that you want the method to wait before continuing.

[IMPORTANT NOTE!]

IEnmumerators require at least 1 “yield” event in order to work!

[EXTRA]

You can put the WaitForSeconds function in between two different statements!

--

--

Adam Reed

Hi, my name is Adam Reed and I am a software engineer specializing in Unity and C# development. Feel free to scroll through and check out some of my work!