Day 14: Coroutines with Unity!
Objective: Spawn enemies using a Coroutine.
To start of spawning enemies we will need to create an empty game object to attach the script to.
Now create the script.
In the Script we need a reference to the game object that will be spawning.
Now we will create a IEnumerator called SpawnRoutine().
This is where we will instantiate the enemy. We want the enemy to spawn above the screen and at random X positions. We need to create a Vector 3 and use random.range for the X position, input the y and z values as well.
Now this will only run once and after one frame. We want it to wait 5 seconds between each spawn.
Now to make it keep spawning while the player is alive. We need to create a bool to know when to stop spawning.
Now we need to use it. We will use a while loop in the IEnumerator to keep it always running until _stopSpawning is true;
This will need to be called start start. What we will do is in the Start() function we will start the coroutine.
The spawning will now continue for ever! What we need to do now is to make _stopSpawning true when the player dies. We do this by creating a public function called OnPlayerDeath and inside this function set _stopSpawning to true.
On the Player script we will need to call this function when the player dies. So first we need a reference to the Spawn Manager.
Next will be to find the SpawnManager and get the SpawnManager component. We will use GetComponent again, but this time we will use GameObject.Find().GetComponent. This will find the object that is passed into Find(). Always a good practice to null check, so we don’t get a crazy error.
We need to call the OnPlayerDeath function now. In the Damage function we created earlier, we need to call it.
And that’s it. The enemies will spawn until the player gets destroyed.