Coroutines In Unity : Spawning Enemies In my Game

PieceofPhie
3 min readMar 27, 2021

--

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.

The Couroutine

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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

PieceofPhie
PieceofPhie

Written by PieceofPhie

Unity Developer Based out of California

Responses (1)

Write a response