Modular Power-up Systems
In the last article, I went over how I implemented the speed boost power-up logic and will now go over how I extended the power-up to support multiple kinds of power ups such as triple shot, speed boost, and shield.
Extending the Power-up Component
In the PowerUp
script, I added in a new enum type called PowerUpType
used to describe what kind of power up the player can pick up. Next, I expose the PowerUpType as a variable called powerUpID
to be revealed in the Unity Editor. The alternative would be to declare powerUpID
as an int
but I would need to add comments describing what each number corresponds to.
Enums can be safely typecasted to int
type where the first entry in the enum (e.g. TRIPLE_SHOT
) will start with 0 and the following enum types will be incremented by 1 based on the previous enum entry’s value.
In this case, TRIPLE_SHOT
will be set to 0, SPEED_BOOST
will be set to 1, and SHIELD
will be set to 2.
Next, I created a nested public static class named Extensions
that contains a static helper method to obtain a random power up type.
In this current implementation, we can easily add more power up types as the game grows. This is because the only spot we need to change in the PowerUp
script is the PowerUpType
enum where we add in new power up types as needed. Another added benefit of using an enum instead of an int
is that Unity Editor exposes the PowerUpType
enum as a drop-down that shows all possible power-up types that can be picked up by the player. This allows for better readability when viewing which powerUpID
to set.
Revisiting SpawnManager Script
Back in the SpawnManager
script, I used the PowerUp script’s extension function to select a random power up to spawn when the SpawnPowerupRoutine()
coroutine runs:
Casting PowerUp.Extensions.GetRandomPowerUp()
from a PowerUpType
to an int
will all us to obtain the index to locate the correct power-up from the powerups
GameObject array. The important thing to note here is that the power up types need to correspond to the order they are presented in the enum.
Reacting to Power-ups
Last but not least, the player needs a way to react when it overlaps with another power-up. This is done through OnTriggerEnter2D
Unity Monobehaviour function. Depending on the powerUpID
of the current Power-up being picked up, the player will call one of its public functions to enable the specific power-up:
Thanks for reading!