Spawning Enemies with Coroutines

Ahad L. Amdani
3 min readMay 19, 2021
Eventually, I shoot them down some but the enemies being spawned is each 1s

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.

The range on the X-axis help spawn the enemy at a random position, anchored to the top of the scene.

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.

Public to the editor, private to other classes
Refactored a bit, to allow for on-the-fly customization by the game designer, and to stop spawning if triggered

And the coroutines are so simply called:

You could also pass in the name of the method as a string, e.g. “SpawnRoutine”

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):

Public method to access a private variable within the SpawnManager GameObject
Wait, where’s that reference to _spawnManager coming from?
Oh, there it is!

--

--