Creating Modular Powerup Systems

It’s time to add more powerups! The creation of more powerups could be tedious if you were recreating everything from scratch again. It is important to remember that you can reuse much of what you have built for past powerups. The most important thing to reuse is the script. To do this first create the new powerup. If you need a review of how to to that you can find it here. For the script you will use the one created for the other powerup. You just need to make some changes to the script so that it can work for any powerups that you implement.

The first change to the script is that you need to add a variable to track which powerup it is. Make sure you give it the SerializeField designation as you will need to change its value in the Unity editor. Now go to the editor and in each powerup prefab give them different IDs. Remember which IDs you assign to which powerup. It can be helpful if you track it with a comment next to the variable declaration.

[SerializeField] private int _powerupID; // 0: Triple Shot, 1:                
Speed, 2: Shields

Next, inside the OnTriggerEnter2D function in the if statement where you check that it you got the player component you will need to create a switch statement to handle the different powerup IDs. You could also use an if statement with else if’s if you know you are not going to use very many powerups, but, this can get messy if you start having too many.

switch (_powerupID) 
case 0:
case 1:
case 2:
Debug.Log("B=Unknown powerup ID");

For each powerup ID you will need to create the corresponding function in your player script. With this done all you need to do is create the animation for your powerup. If you need a reminder on how to do that you can find it here. Now you are setup to handle as many powerups as you want.

Good Luck Adventurer!