Spawning Multiple GameObjects At Random In Unity3D

Pete Thomasberger
3 min readMay 21, 2021

Objective: We will add the Speed Boost power-up to the SpawnManager script and instantiate the Triple_Shot_Power_Up and Speed_Power_Up Prefabs at random using an Array.

Step 1: Create Power-Up Variable Array

In the SpawnManager script, delete the _tripleShotPowerUp variable. Utilizing [SeriaizeField], create a new private GameObject variable, add open and closing brackets [], and name the variable _powerUps.

Note: Using [] after the variable type declares that this variable is an Array. Using an Array is a great way to manage two or more variables of the same type.

Step 2: Instantiate the Power-Up Array

In the PowerUpSpawnRoutine() method, create a new local variable of type int called randomPowerUp and have it equal to Random.Range(0, 2). Since we currently have two power-ups, the range of the Array randomness will be between 0 and 2.

Note: We only have two power-ups in the Array, and the Triple_Shot_Power_Up Prefab will be assigned the value of 0, and the Speed_Power_Up Prefab will be assigned a value of 1. But because we are using an integer value for the range, we must use one more value than what we need. For example, if we had three power-ups, the code would need to say Random.Range(0, 3).

Next, in the instantiate statement, replace the _tripleShotPowerUp variable with the new _powerUps Array variable and add brackets [] to the end of the variable name.

Within the Array brackets, call the randomPowerUp variable.

Here is what the entire updated PowerUpSpawnRoutine() method will look like:

This method now states that we want to instantiate a random power-up GameObject every 3 to 7 seconds from a starting position of 7.5 on the Y-axis, and between -9.4 and 9.4 on the X-axis.

Save the script and go back to Unity.

Step 3: Assign Power-Ups to the Array

In Unity, select the Spawn_Manager GameObject from the Hierarchy window. In the Inspector window in the Spawn Manager (Script) component, click the disclosure triangle next to Power Ups and add two Array Elements by clicking the + button. First, select the Triple_Shot_Power_Up Prefab in the Project Window and drag it into the Element 0 slot. Then select the Speed_Power_Up Prefab and drag it into the Element 1 slot.

Play the scene, and the Triple_Shot_Power_Up and Speed_Power_Up Prefabs will spawn randomly every 3 to 7 seconds.

--

--