A Picture in Motion — Using Coroutines in Unity
--
Coroutines are special functions in Unity that allow a series of commands to run when desired, and halts them when the conditional is not met. These are a core building block of several different mechanics and concepts in game design!
Let’s make a spawning system for our enemy to show off how to utilize the coroutine.
First off, make a new empty gameobject in Unity to be our spawn manager. This empty object’s function is to hold a new script we will be writing, as it needs no physical form.
Next, create a new C# script and name it appropriately. I named mine SpawnManager.cs
Attach this script to the Spawn Manager Gameobject by dragging the script onto the gameobject.
Now let’s open up the C# script in Visual Studio.
First I set a few variables we will need to track in order to make the spawn manager work as intended.
For this example, I want a spawn system that:
- Only spawns enemies when the player is alive.
- Spawns enemies off screen at a random X position (Enemies move down the screen from top-to-bottom.
- Spawns a new enemy every 2 seconds.
First off, I set three gameobject variables:
- The player gameobject
- The enemy prefab
- A container to hold the enemies in (more on that later)
With these variables set, it is time to start the coroutine.
NOTE: All coroutines must include certain key phrases to operate correctly. If the contents of the coroutine do not include any coroutine specific diction, you will get errors (and you should use a normal function instead).
I use a “while” command to set up the function to only play while the player gameobject exists. This means that if the player is destroyed, anything inside this coroutine will never happen.
Next, I set a local variable inside the coroutine to hold each enemy’s spawn position (aptly named enemySpawnPosition)
Next, the actual instantiation of the enemy itself. Each enemy instantiated is held in another local variable called newEnemy.
Finally, the delay timer to ensure this doesn’t happen every frame (60 times a second).
Now we want to start the coroutine in Void Start as we want this to run for the entirely of the game.
Now set your variables in the Inspector in Unity and test it out!
As desired, enemies spawn on a 2 second cooldown at a random position offscreen!