Modular powerup system in Unity with a switch statement

My objective is to add a speed power up and manage it within the scripts utilizing a switch statement.

I’m going to start off by creating an integer for _powerupID within PowerUp.cs, in order to manage differentiating between the different types of powerups, this will allow me to identify which powerup is which by setting the _powerupID within the Prefabs which are attached to this script.

So, to handle determining which I’ve picked up, of course, I could use an if-then with else-if statements to slowly narrow it down… However, the more data you sort with this, the bulkier it’s going to be. That’s why we have switch statements. The two statements below are equal, but one is clearly more efficient than the other.

I’m going to delete the if-then statements and rely entirely on the switch. Now I have to actually handle the effects of the powerup within Player.cs within the following:

Now, this is all old hat now, but I still have to control the speed.

Now… I’m a sucker for being able to tune everything directly, so while there’s several ways to go about this, I’m going to create another variable for the specific speed of the speed boost, but I’m defaulting it to 10.

This is one of many methods to accomplish this.

Now, I’m gonna test it out to see how well it works!

Perfect! All that’s left is spawning and animating it.

To spawn it, I’m going to be using an array instead of hardcoding the spawn like we are currently. Arrays appear as lists in the inspector, which can handle many things things at once.

To create one, I just need to add brackets[] to the GameObject I’m denoting at the beginning.

Then it’s a simple matter to edit the spawn code to accept it and make it random, creating a randomPowerUp integer and then calling it with powerups[].


All that’s left is the animations, which I examined recently.

Time to take another look at my current game.

I’m gonna be adding the shield powerup tomorrow, be sure to check back for that.



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