What are Coroutines?
Code that’s called inside of Update takes place all at once during the current frame. On the other hand, Coroutines allow you to execute game logic over a number of frames.
They allow you to pause a function and tell it to wait for a set amount of time or wait for an action to occur before continuing.
Now that we have our Player ready and our enemy spawning… now we need... an actual challenge - you just beat the ‘game’ in one touch or by shooting your laser once at the enemy. Not very fun, is it?
What we are going to do, is to create a new empty GameObject called ‘SpawnManager,’ to which we will add a new ScriptManager script.
We will move the Enemy spawn code to a new method in this script, which we will call SpawnEnemy().
Let’s break this code down…. I have created a Serialized GameObject variable for my enemy prefab. This will be used in our new method. In this method, I will assign a new variable with a random position to spawn our enemies and then Instantiating the enemy prefab on that location. Since we want to spawn multiple enemies, I will be calling this method in the Update loop. But is this correct? - Let’s see!
Ouch, I don’t think we can handle that many enemies now that we have implemented our cooldown system!
But why is this happening? - well, that is because we are running our SpawnEnemy() method inside the Update loop, which gets called every frame, and that is 60times per second.
And this is why we will have to use a Coroutine! - the name of our coroutine will be SpawnEnemyRoutine() since we want to be ‘Spawn’-ing enemies.
To declare a Coroutine, the method needs to be of type IEnumerator from the System.Collections namespace.
One key aspect of the Coroutine method is the ‘yield’ statement. The ‘yield’ line is the point at which execution will pause and be resumed in our case after one second. This is how we can spread out the execution of our code.
We will now move the code from our SpawnEnemy() method into the new SpawnEnemyRoutine() coroutine!
Now, all we need to do is to make some minor adjustments to our code. Here I will create a Serialized variable _spawnInterval - this variable will control how often the enemies can spawn and can be adjusted via the Inspector.
Finally, we have to delete the call of the SpawnEnemy() method in our update loop and instead call our new SpawnEnemyRoutine() Coroutine… - but wait! We have to move it from our Update loop into the Start method because it would still get called every frame.
And this is our final code — now our enemies will be spawning in 5-second intervals, which we can freely adjust in our script or the Inspector.
Other ways of starting a Coroutine
There are different ways to start a Coroutine, each with various benefits.
If you wish to know more about Coroutines, click here!
But that is it for now, thank you for reading and feel free to follow me for more articles — and as always, good luck and see you next time!