Creating Modular Powerup Systems

Instead of creating a separate script for each powerup in my 2d space shooter game I use one that has a _powerupID int variable that I can assign in the inspector.

I then use an Action and pass an int (the _powerupID) to my Player class which is subscribed to the Action named OnPowerupCollect.

I invoke the Action when the powerup collides with the Player.

(Instead of destroying a powerup every time it’s collected and creating garbage collection/memory allocation I will implement object pooling to recycle them before I’m finished with this game, so the code will look a little bit different when complete.)

In my Player class I have a method named PowerupEnable(int powerupID) which is subscribed to the OnPowerupCollected Action in the Powerup class.

(with using System; added to the namespaces at the top of the script you’re able to use and subscribe to delegates and events, Actions and Funcs. )

This PowerupEnable(int powerupID) method has a switch statement that calls the correct method or coroutine needed for each powerup depending on which powerupID was passed from the Powerup class when the OnPowerupCollected Action was invoked.

I use a switch statement instead of a bunch of if else statements to keep the code clean.

As you can see using switch statements and Actions allow you to create a nice clean modular powerup system.

Unity Developer/C# Programmer for VR, 2d,3d Games and other Immersive Interactive Experiences