Now hold on a second!
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.
What is a Coroutine?
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.
Yield return null
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.
Yield return new WaitForSeconds(int)
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.
Yield return new WaitUntil
This flavor waits for a condition (returned by a delegate) to resolve to true.
Yield return new WaitWhile
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.
Yield return new WaitForEndOfFrame
This yield statement waits until all the visuals have been rendered before continuing.
Yield return StartCoroutine
It is also possible to wait until another coroutine has completed running.
Using a coroutine in our Spawn Manager
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 gamedevchris.medium.com.