Creating Modular Powerup Systems
Objective: Figure out how to use just one script for all the power ups.
Now that I have more than one power-up, I need to decide if I want each power up to have its own script or try to use one script for all power-ups. The answer is one script since all the power-ups have the same behaviour.
To use just one script, we will need to make some changes. The first is to add a variable to store an ID to keep track of the power-ups. I have chosen _powerUpId.
I have added the serialized field attribute so I can assign the ID in the inspector.
Now that we have the ID set for each power-up, we can move on to the logic for calling the appropriate method when the power-up is collected.
For this, I will use if else if statements to check the power up ID.
Below you will see the script in action, when the triple shot is collected the player can shoot the triple lasers and when the speed boost is collected the player moves twice as fast.
You may be thinking this method could get out of hand if had more than just a few power-ups and you would be correct.
Let’s say you had 10, 20 or even 30+ power-ups, it would be ridiculous to have 30+ else if statements. Luckily there is a better way, I will show you in my next article.