Creating Modular Powerup Systems

Within a project, it is essential to keep the code clean, meaning that it is self-explanatory and there is no waste of resources.

Some examples within Unity can be to always leave the Update function easy to read, calling methods instead of inserting many lines of code and then not remember what they are for.

When I made the power-ups for my game I thought about these things. I created my to-do list with the pseudo-code and I realized that the behavior of the object was always the same, only the final effect on my player changed.

So let’s analyze the behavior of power-ups:
1.Spawn in the upper part of the screen.
2. Go down vertically and destroy themselves on contact with the player or if they come out from the bottom of the screen.
3. Depending on the type of power-up we need to activate a specific behavior of the player.

1. Spawn in the upper part of the screen
The first point will be managed by the spawn manager that already manages the appearance of enemies.
We write a coroutine identical to that of the enemies, the only difference is in the “Instantiate” because we have 3 types of prefab instead we had only one enemy. We solved it easily using an array.

Then we add to the list of prefabs that can appear the new power-ups, we scan the criteria with which they will appear and that’s it.

2. Go down vertically and destroy themselves on contact with the player or if they come out from the bottom of the screen.
This is very simple, we write our method that provides that the power-up descends vertically at a speed defined by Inspector marked in seconds and after a certain lower limit is destroyed.

3. Depending on the type of power-up we need to activate a specific behavior of the player.
There are three types of power-ups, but if there were fifty it wouldn’t change. We manage the collision of our object with the method OnTriggerEnter2D, remember that the power-up and the player must have their collide connected and the check isTrigger active.

C# provides us with a method to handle multiple choices, the switch, thanks to this tool we can define different behaviors with a few steps.
To move forward we need to get a reference of the player to access its public functions and assign our power-ups a numeric identification value.

Finally, we must remember to destroy the power up after it has been collected by the player.

Happy Easter!