Spawning Objects from an Array

We now have 2 Powerups, and we obviously want to Spawn them, kind of like the Enemy spawning. But, we don’t want to have to create a Coroutine for each Powerup, because, it’s totally unnecessary!

In this article we’ll cover the power of an Array, and how to use them properly!

Spawning from an Array of Powerups!

Spawning One Object (Triple Shot)

Inside our Spawn Manager script, we’ll create our logic for Spawning one Powerup to get us started:

Coroutine logic for spawning our Triple Shot powerup.

And call the Coroutine in the Spawn Manager Start() function alongside our Enemies.

Start our new Coroutine.

Always remember to link your Prefabs in the Inspector too!

Triple Shot Powerup linked in the Inspector

And our Powerup Spawning in action!

Powerups for everybody!

Creating an Array

What is an Array? — It’s a set list of objects.

When creating an Array, you declare it by using square brackets of the Type Variable you are creating the Array for, followed by the name:

Creating an Array of GameObjects called powerupsArray.

This Array is [SerializeField] so that we can input of our Objects in the Inspector:

Fixing our Array in the Inspector

Spawning from an Array

Inside our SpawnPowerupRoutine() we’ll create a Random int value to Spawn a random Powerup from our Array.

Inside the square brackets is the index (the object you want to spawn) of the array.
  • It’s important to remember when using Random.Range, that when using int values the second number is EXCLUSIVE. So while we wrote the random range to be between 0 and 2, it will only be between 0 and 1.
  • If using float values however, the second number is INCLUSIVE, meaning that the range would now be 0, 1, or 2.

When instantiating from an array you must include the index number of the object you want to spawn. As such, powerupsArray[0], spawns the first object in the array. While powerups[1] spawns the second object.

The index number can be replaced by any variable, such as the randomPowerup variable we have created!

Now we can Spawn Powerups from our Array, making some variety, and randomness, for our Player to interact with!

SpawnPowerups from an Array working properly!

Next we’ll be covering Animating our Powerup Sprites to really make them POP!

Audio Engineer turned Unity Game Dev. Will be combining both my skillsets when appropriate, and will be documenting my Unity Dev growth in these Medium Articles

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