Coroutines With Unity!

Austin Hall
2 min readSep 22, 2022

--

Coroutines allow us create sequenced events that allow us to yield events. think delayed spawn, choreography or playing animations.

to create a Coroutine, we create a method of type IEnumerator. Inside this method we will use the concept of the “while loop”.

Example of an Infinite loop

The danger with the while loop is that you can, very easily, create an infinite loop. It will take up the entire memory footprint of your computer. this can, and will, crash Unity, and possibly even your computer.

In this example, the while loop will execute when the condition “true” is met. Well… true will always be true. So, when the while loop is executed the first time it will continue to run infinitely.

Instead of putting the while loop in by itself, we need to give the computer time to breath. We accomplish that with a Yield Event.

Our SpawnRoutine() method is of IEnumerator type. this is required to run the coroutine. The While loop will run as a coroutine and the yield event will spawn an enemy every 5 seconds while the rest of the program continues to run as normal.

--

--

No responses yet