Now hold on a second!

Image by Jan Persiel — Get this image on: Flickr | License details

Today we’re working on spawning enemies! We don’t want to spawn enemies (or power-ups later) all at the same time or every frame. If we did, we would end up with a never ending wall of enemies. We need a way to spawn an enemy based on a time interval. Enter Coroutines.

A coroutine in unity is a function that allows us to execute code across multiple frames or in response to something else happening in our code. It has a return type of IEnumerator and includes one or more yield statements.

The yield statement is what allows Unity to place the coroutine on hold and then pick up execution of the coroutine from the same point later. Yield statements come in a few flavors and which one you use depends on what you are trying to accomplish.

We can use yield null when we want Unity to simply wait until the next frame. When combined with while statements you can create a situation that operates much like a list of tasks.

We use this type of yield when we want to pause the execution of our code for a specific amount of time, This is the yield we would use to wait for a number of seconds before spawning our next enemy.

This flavor waits for a condition (returned by a delegate) to resolve to true.

Like WaitUntil, this yield statement waits for the return boolean value from a delegate, this one waits for the return to be false. Note that I used a shortened inline version of the delegate here.

This yield statement waits until all the visuals have been rendered before continuing.

It is also possible to wait until another coroutine has completed running.

For our purposes we are going to move our spawn code into a coroutine, named SpawnEnemyRoutine, and trigger it with StartCoroutine in our Start() method.

Today we looked at what coroutines are, and how we used them in our spawn manager. Tomorrow, we will look at spawning all these enemies without cluttering up our Hierarchy! If you enjoyed this article, or want to come along with me as I progress on my journey, follow me at

Unity Game Developer, Software Engineer, Gamer, Musician, and Father. Christopher is a creative that enjoys a challenge and loves coding.