Creating Modular Powerup System

The more the better

A game without powerups is a very boring game. Then again if you only have one powerup it isn’t that great. So we make several powerups for our game, for example, in our case we will have a TripleShot, a SpeedBoost and a Shield.

Powerups

We already have the TripleShot powerup using the Powerup script. Now, is it necessary to writte a specific script for each powerup? NO.

We can create a Modular Powerup System using the inicial script.

Right now, the OnTriggerEnter2D method is checking if the other.tag is Player and Player isn’t null, then it calls the TrippleShot method in the player script.

Calling the TripleShot()

We need to modify this so that we can check for the different powerups we have available.

Lets organize our powerups in the following manner:

  • 0 = Tripple Shot
  • 1 = Speed Boost
  • 2 = Shield

In our Powerup script, we need to create a serialized variable to hold this value for each powerup.

powerupID variable

No we need to modify the OnTriggerEnter2D method. Since we have to check the value of _powerupID, we can use an if else if statement.

if else if statement

If we run this, the only option that will actually work is the TripleShot because it is the only powerup we have scripted. Once we script the other two powerups, we can call them from here and it should all work great.

Back in Unity, if we check our two Prefab / Powerup objects, SpeedPowerup and TripleShotPowerup, we notice that in the Powerup script in the Inspector, we now have a Powerup ID set to 0 as default. This is fine for the TripleShotPowerup since we assigned it to 0 but we need to change it for the SpeedBoost prefab object and set it to 1. Eventually when we create the Shield powerup, we will set it to 2.

Changing the Powerup ID assignment

This works fine although aesthetically the if else if statements are a little hards to follow. What if we had 50 powerups? Do we want to write out 50 if else if statement. I wouldn’t think so.

In my next article I will go over a better option to the if else if statement called the switch statement. It is easier to read and write.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store