Creating Modular Powerup Systems
Adding elements of chance makes games fun. Our game already has enemy ships appearing in random locations. Let’s spice up our Space Shooter by making the PowerUps appear in random order. First we’re going to need to change the PowerUp GameObject variable to an array, and then we can assign the PowerUps as elements in the array using the Unity interface. After that, we just need to randomize the selection of the array elements at instantiation.
Using arrays in Unity couldn’t be easier. Changing our _powerupPrefab GameObject inside the SpawnManager to an array of GameObjects is done by adding array brackets to the var type:
The Unity interface gives us a drag-and-drop style assignment method for arrays. Let’s tell Unity which PowerUps are associated with each element of our new array of GameObjects by assigning them in the Inspector tab:
Now we can introduce a random variable and use it at instantiation: