In Sovereignty, we want to spawn enemies in a random position at the top of the screen, for the player to engage as they automatically move down the screen. As we know, if we let the enemies fly down to the bottom, they re-spawn at a random position at the top of the screen and begin the process again. Since out enemy behavior is already defined in such a way, unless we want to hand-place enemies into the scene or “level” then we need to spawn those enemies in an effective and efficient manner. Enter coroutines.
In this coroutine called “SpawnRoutine” we create an infinite loop that yields the block for 5s (changed to 1s in the video) with the WaitForSeconds method before executing the next iteration to spawn the next enemy. I’ll change that and the ranges to variables later, that are serialized, so we can dynamically adjust the spawn rate and the range of X positions for which enemies can spawn.
And the coroutines are so simply called:
This allows the game/scene to run a method (coroutine) in a never-ending loop without eating up all the system’s resources while appropriately allowing for randomized enemy spawning. Now, the last thing to do is to end the spawning when the player has “died” (we’ve refactored the while loop to leverage a _stopSpawning variable, which is triggered by an OnPlayerDeath() method in the SpawnManager script):