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 One Object (Triple Shot)
Inside our Spawn Manager script, we’ll create our logic for Spawning one Powerup to get us started:
And call the Coroutine in the Spawn Manager Start() function alongside our Enemies.
Always remember to link your Prefabs in the Inspector too!
And our Powerup Spawning in action!
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:
This Array is [SerializeField] so that we can input of our Objects 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.
- 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!
Next we’ll be covering Animating our Powerup Sprites to really make them POP!