It’s been over two years since I started learning game development in Unity. One of my first projects was a 2D space shooter game with power-ups that gave the player extra speed, a triple shot, shields, etc… I have decided to revisit the power-up mechanic and expand upon it. I’ve added another level of modularity to it. This post will explain what I’ve done.
My first goal was to make the overall effects of each power-up modular. So I created a scriptable object class called ‘PowerUpEffect’. This class contains an Enum to determine which stat is affected, a float, a bool, and a color. The float is used for stats like speed, and the bool would be used for something like turning on shields. The color is there to determine the color of the power-up.
Next, I created a class called ‘PowerUpInstance’. This script inherits from Monobehavior and will be attached to the actual power-up game objects.
I want the power-up objects to change color based on which stat they affect. So, in Start, I get a hold of the material component on the mesh renderer. Now, here’s where I expand upon basic power-up functionality. I created an array of the PowerUpEffect class. This means that one instance of a power-up can have sort of a combo effect. If there’s just one effect, the object’s material is assigned the effect’s color. However, if there are two effects, in Update, I used the Color.Lerp method to change from one effect color to the next. Within the Lerp, I used Mathf.PingPong to make the colors change back and forth.
Then, to actually give the player the effects, I used OnTriggerEnter for collision detection. Within this method, if the colliding object has the tag “Player”, a foreach loop is used to trigger each effect in the PowerUpEffect array.
With the code for power-ups done, I need to set up the actual game objects. So I used a basic capsule, attached my PowerUpInstance script. Next, I created some PowerUpEffect Scriptable Objects, assigned which stat they affect, and then gave them values. I can now place these assets in the PowerUpEffect array via the inspector.
Powering Up the Player
Finally comes the part where the Player’s stats are affected. For this, I created a TriggerPowerUp method that takes in the enum for the StatAffected, and the PowerUpEffect being triggered. I then use a switch statement to match up the effects with the Player’s stats. There’s some UI stuff in there but that’s just for visualization in the demo and not crucial.
The final result is that power-up objects can give the player multiple effects. Maybe you want to boost the player’s speed at the cost of health? Or maybe every time the player gets a certain Health power-up, their speed is temporarily reduced. This system allows for a lot of customization in how power-ups are implemented. Then, there’s the color-changing aspect that makes them more visually interesting. This part could also be expanded upon to include material lerping and other interesting effects.