Using Arrays To Spawn Powerups
Spawning The Powerups Randomly
Speedboost is only our second powerup, TripleShot was the first. In our SpawnManager script, we can see that we have hard coded the spawning of the TripleShot.
We could do this for each powerup because we only have three, but imagine if you had 30 or 40 powerups in your game! This would be pretty tedious.
So, to make this easier and less coding intensive, we can make some changes and use a GameObject array to hold our different powerups and then we can use the label each powerup has to randomize their spawning in the game.
We will need to change our GameObject variable in the SpawnManager script to a GameObject array variable.
The  indicate it is an array object.
If we go back into Unity, selecting the SpawnManager object, we can see that there is a new element in our Spawn Manager script called Powerups.
By selecting the arrow next to it, we get the option to create our array.
We can put as many items in our array as necessary. We are only going to have three powerups so I set it to 3.
Now we need to add our powerups to this array. Remember in our Powerup script, in our switch/case statement, we set TripleShot to 0, SpeedBoost to 1 and Shield to 2.
Knowing this, we need to place our powerups in our array in the same order.
Now, in the SpawnManager script, we need to make some changes to the SpawnPowerupRoutine coroutine in order to randomize the spawning of each powerup.
First, we need to create an integer variable to randomize the numbers 0 to 2.
Now, in the Instantiate we need to call our array GameObject and pass in the random number just generated.
If we put this coroutine together, we get
In order to call an item in an array, we call it by name and pass in the position of the item we are looking for.
- _powerups ….. Calls the triple shot powerup
- _powerups ….. Calls the Speed boost powerup
- _powerups ….. Calls the Shield powerup
Now, if we run our game in Unity, the powerups should appear at random.