Made With Unity | 2D Space Shooter Part 5: Spawning Enemies
In this series of article / tutorials we are going to be making a small 2D Space Shooter using Unity3D and later on using the New Input System.
Organizing The Hierarchy
Create 3 new empty GameObjects, one of them will be named [ — MANAGERS — ], the second one SpawnManager and the third will be called [ — ENEMIES CONTAINER — ]. Drag the SpawnManager object inside the [ — Managers — ] object.
Spawn Manager Script
Create a new scrip calling it SpawnManager and type the following code using the image below and add the scrip component on the SpawnManager object on the Hierarchy. On the Enemy Prefab field select the Enemy prefab from the Prefab folder on your project windows and the Enemies Container will be to drag the [ — EnemyContainer — ] object to the empty field.
On the SpawnManager scrip we are introduce to a Coroutine named IEnumerator SpawnEnemy on line 19 to 30, that we start to called on the Start() method on line 16. Using Coroutine we can repeat a block of code for a giving time and telling it to make a brief stop and continued using what is on line 28 yield return new WaitForSeconds(), we are spawning enemies every 2.5 seconds. The IEnumerator SpawnEnemy will continued to spawn enemies as long has the Player is alive, once the Player reach 0 lives it will stop; hence the reason we have a public method called IsPlayerDead(), line 32, when the Player dies he will communicate with the SpawnManager script and tell the IsPlayerDead() method if he has died.
Updating The Player Script
On line 24 were making a variable to have reference to the script SpawnManager, then on the Start() method where are getting the component, line 30, in order to have access to any public method. Line 77 we are communication with the SpawnManager script and calling the public method IsPlayerDead() and passing a value of true to let the SpawnManager know that the Player is dead, stopping the SpawnManager in continuing spawning enemies. The remaining enemies will just continued to change position.
🎮TO BE CONTINUED 🎮