Coroutine in the Spawn Manager

David Little
3 min readJul 17, 2021

For our game, we want to shoot at enemy ships. We do not want to shoot at only one, though. We also do not want to shoot at five thousand of them all at once. We need a way to spawn a number of enemies that is challenging but not overwhelming to the player. Enter, the coroutine.

The name Coroutine says it all. In general, two or more routines (functions/methods) that run together, but dependent upon each other. In unity specifically they are used to increment one function over several frames of time with a ‘yield.’ That is to say, that one function, usually a while loop, is allowed to do its thing and then stop for a predetermined amount of time before continuing again, for the length of the game or until a condition is met. In this case we want to tell the game to create a certain number of enemies for the player to shoot at and we want those enemies to be created at a specific rate.

The method for Unity is the IEnumerator and the syntax looks like this.

The previously mentioned ‘yield’ lets you pause your function for a period of time. You pair that up with something that defines the time, like WatiForSeconds. The result is a function that does ‘its thing’ in intervals equal to the time defined. If that time was say 5 seconds, it would look like this…

Now we combine the two into a complete script, the Spawn Manager.

We next need a variable that can be used to check and see when we should stop spawning enemies. We’ll call that one, descriptively, _stopSpawning.

We then need to call that variable in a new routine called OnPlayerDeath. This new routine is the condition that must be met in order for our while loop to stop completely. So that, as long as the player is alive, the SpawnManager will continue to spawn enemy ships, until…the player is dead.

Our final script, with all of this is put together and looks like this…

Next we’ll be adding in assets to transition this game from prototype to production.

--

--