In this article we’ll explore making a modular power-up system for your game. This way you can have a single script acting as a container for every power up you make instead of making a ton of different and unique ones. Start by opening up Unity or creating a new project.
First we’ll start by creating an empty object called Speed Boost in the Hierarchy, and then we’ll create a Script called (you guessed it) PowerUp this will act as the container for our power-ups in the game. Attach PowerUp to Speed Boost before we forget like so.
Then in PowerUp we’ll create a enum at the top of the script outside the class called PowerUpType and then enclose three types of power-ups in brackets, spaced by commas. I went with SpeedBoost, Firepower, and Invisibility, you can pick whatever you like but you must have atleast one.
Then create a private serialized variable that will hold which type this power-up will be like so.
Next we’ll create a OnTriggerEnter method that will react when the player hits the power-up, then use a switch statement to determine which power-up will trigger on the hit. We’ll destroy the power-up after for visual feedback.
Now head back to the editor and we’ll set up the power-up to utilize this new code on the inspector. Make sure the drop down reads Speed Boost.
Now we’ll give the power-up a Mesh Filter (I used a Cube) and a Mesh Renderer as well as a Box Collider. Set the Collider to Trigger so that the player will trigger it when they enter.
Here it is in action.
Now let’s make it affect the player’s speed. On my player character I have a script that has a public speed variable. Let’s double it from the power-up script.
Let’s test it again.
Going from 100 speed to 200 speed is a snap. There you have a very easy, straight forward, and most importantly modular power-up system. Here is the full code snippet
Now you have a very extensible system that you can keep self-contained. Simply make the changes you want, prefab the power-up, and then spawn as appropriate. Until next time, happy coding.