My journey becoming a Unity game developer: Using a Spawn Manager for Galaxy Invaders pt.1
Objective: Create a Spawn Manager for the enemies to spawn from. Make the enemies spawn from random positions along the X-axis every 5 seconds.
We want our enemies to spawn from above the screen to attack the player. To begin, create an Empty game object name Spawn Manager. Reset its Transform positions to zero. Then, create a C# script name SpawnManager and attach this script to the Spawn Manager game object.
Inside the SpawnManager script, use the IEnumerator to create a new coroutine name SpawnRoutine(). Inside of SpawnRoutine(), we want to check WHILE enemies spawning is True, instantiate the _enemyPrefab at the Spawn Manager object’s position. Then, Yield and wait for 5 seconds before spawning another enemy.
Now for the SpawnRoutine() to work we must Start the coroutine in the Start() function. This will begin spawning enemies as soon as this script is activated which will be at the start of the game.
With the Spawn Manager selected, in the Inspector we will drag the Enemy prefab from our Prefabs folder into the Enemy Prefab slot under the SpawnManager script component. Notice when playing the game that the enemy is spawning every 5 seconds, but in the middle of the screen from the Spawn Manager object.
If you tried the SpawnRoutine() inside of the Update() function, this will spawn enemies 1 per frame which will be 60 frames per second. Can we say Enemies overload!
We don’t want our enemies to start spawning from the middle of the screen only. Instead, we want them to spawn randomly along the X-axis from the Spawn Manager game object.
Let’s create a new Private Float with a SerializeField attribute variable name maxXpos with its value set to the default of zero. This will represent the maximum position along the X-axis the enemies can spawn onscreen. Also, change the _enemyPrefab variable to Private with a SerializeField and an underscore to show it’s a private variable.
Inside the WHILE() statements under SpawnRoutine(), create a new variable Type Float name randomX. Set its value to a Random Range of -maxXpos and maxXpos creating a boundary for the enemies to spawn. Now create another variable Type Vector3 name spawnPos for the spawn position of the enemies. Set its value to a new Vector3 positions of the randomX variable on the X, the Spawn Manager object’s transform position on the Y-axis, and zero on the Z-axis.
Inside the Instantiate() method, replace the transform position with the randomX variable as this will spawn the enemies from random positions along the X-axis. Make sure to change enemyPrefab to _enemyPrefab as this is the new spelling.
Now our enemies are spawning from random positions on the X-axis from the Spawn Manager game object.