Creating a Modular Powerup System in Unity
Objective: To create an efficient modular powerup system to our 2D Galaxy Shooter game in Unity!
Is there a reason to create a powerup script for each individual powerup when they each have very similar functionality? No of course not! If we are able to modularise our powerup script, why create much more work for ourselves when we can simplify and get the same result.
Let’s have a look at using the same ‘Powerup’ script but identifying each individual powerup using a powerupID, so that when the player collides it will uniquely identify which powerup has been collected and which method should be run accordingly.
Within our ‘Powerup’ script, let’s add some code:
So here we have created a new private int variable called powerupID which we are going to assign a number to for each powerup so it can uniquely identify them. Using SerializeField will mean that the private access modifier becomes visible in the Inspector and we can make changes where needed.
So when we collide, IF the powerupID is equal to 0, then run the TripleShotActive() method from the ‘player’ script, ELSE IF, the powerupID is equal to 1, then run the SpeedBoostActive() method from the ‘player’ script etc etc.
Let’s add some Debug.Log into our code and see if it works as intended:
Fantastic!
We now have a modular powerup system where we can simply add a new powerupID to a new powerup. No need for individual scripts for each one!