Unity: Creating a modular powerup system

Creating a modular powerup system will allow us to use and maintain a single script for all of our powerups, with a simple change in the inspector. Here’s how we can set it up.

First we need to setup an ID system for the powerups to distinguish between them when collected.

We create an int in the powerup script and serialize it so it can be edited in the inspector in Unity. Each powerup will have a different value for this.

In our OnTriggerEnter2D method we can add the above if-else statements to check which powerup the script is attached to, based on the assigned ID. Coding for the speed and shield powerups will be added later. We could make the final statement a default ‘else’ but this leaves room for easy expansion of the powerups later.

And there we have it. We can now apply different conditions when we collect different powerups, without the need for separate powerup scripts.

There is a different and potentially better way to implement this, especially if we intend to have many different powerups. I’ll cover that in the next article.

Software developer in the field of Unity and C#. Passionate about creating and always driven to develop.