Coroutines In Unity : Spawning Enemies In my Game
What are Coroutines?
Coroutines is a function that is able to pause execution until its given timer or YieldInstruction(WaitForSeconds()) is finished.
Here's an example of how I used coroutines for my new spawn manager script.


unlike functions, coroutines needs to be declared as a ienumerator since unity’s coroutine type utilizes the .netframework ienumerator type that handles pausing iterations.
This Ienumator contains an open while loop that instantiates an enemy game object in a random X position bettween -8.20 to 8.20 with a Y of 8 then it meets with the WaitForSeconds Yield which is passed a float variable named , ‘time’. The time variable equals 5 so our while loop will iterate again until 5 seconds have passed.
This coroutine is executed in Awake() so we can simply begin the while loop. Its placed in awake() rather than Update() because update will end up repeating our while loop and restarting our timer over and over again. Having it in update will yield something like this.

not a feature I want in my game at the moment so lets keep update from pulverizing our cpu

Our while loop only runs if the player is still alive. We check if our player is alive by using a private boolean variable named ,’IsPlayerDead’ within our SpawnManager script.
Our player script will communicate to our SpawnManager script when the player is dead and will flip the IsPlayerDead boolen to true.
I let the Player script manipulate the private variable by allowing the script to access a public function called OnPlayerDeath().

In the Player script, I have the SpawnManager globally reference in the script. Then I have a local variable within the start method to find the spawn manager game object. Start method then runs through a null check to see if spawn manager exists. If spawn manager exist, we assign our reference variable to the gameobjects component,’SpawnManager’ which is its script. Since we have declared this reference globally, we can now have access to the SpawnManager script throughout our Player script.

We’ll be calling the SpawnManager’s OnPlayerDeath function when the players health reaches less than zero.

OnPlayerDeath will simply flip the IsPlayerDead bool to true which will close the while loop within the Ienumerator. Thus stopping additional enemies to spawn when the player is dead.