Unity — Create a Modular Power-up System
As I outlined in a previous article, power-ups can improve gameplay, and I highly recommended that you implement them. But you will want to have more than one type of power-up to make your game more interesting. You may have an increase speed power-up or a better weapon power-up.
One way to implement multiple power-ups is to create a separate script for each one, but let’s look at putting them into a Modular System that can be adaptable.
Let’s create a single script to handle which power-ups as been activated by the Player. For this example, we will be triggering the power-up when the Player collides with the associated GameObject. Let’s start by creating a variable to identify the power-up.
private int _powerUpId; //0 = Triple Shot, 1 = Shield
We assign this script to each power-up GameObject and modify the inspector’s value to relate to the specific power-up. We have set 0 in the example below because the GameObject is for the Triple Shot Power Up. Repeat this for each power-up GameObject.
With all the power-up GameObjects assigned a powerUpId, we return to the PowerUp Script and add the OnTriggerEnter2D function with an if statement based on the activated power-up.
The above example will run the associated power-up public method within the Player script.
In the next article, I will cover how to clean up this code with a switch and randomly instantiate the power-ups in your game.