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.

Hard coding Instantiation of a prefab

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.

Instead of

we need

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.

Creating an array with three objects

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.

Switch/case statement

Knowing this, we need to place our powerups in our array in the same order.

Draging powerups into array

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

Coroutine to randomize powerup spawning

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[0] ….. Calls the triple shot powerup
  • _powerups[1] ….. Calls the Speed boost powerup
  • _powerups[2] ….. Calls the Shield powerup

Now, if we run our game in Unity, the powerups should appear at random.

Random Powerup Spawning

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Marc Frappier

Marc Frappier

Poultry Scientist by profession, Computer Scientist at heart. After many years in the poultry business, I have decided to give my passion for technology a shot.