Creating A Modular Powerup System
Whether your character is becoming overwhelmed with zombies, a fleet of inter-galactic pirates or a hail of gun fire, a powerup can make the difference between life and death.
The more variety of powerups you create, the more options a player has…but it can also mean more headache if not implemented in a modular format.
For example, let’s say that you want a firing upgrade and also a speed boost for your player:
It wouldn’t really make sense to have multiple scripts for each upgrade…especially if you have 10s or even 100s of powerups. If you were to create a new script for every one, you would at best limit the number of powerups and at worst, make it extremely difficult to troubleshoot any bugs. In both cases you can cripple the play experience.
A better solution is to have one script for all powerups with a unique id or enum that differentiates the powerups:
Seeing as each powerup has the attributes in terms of speed/collision/etc, we can use this to our advantage by passing a unique qualifier to the player to activate the specific powerup.
First we can add the prefab for each powerup to our player:
Then we create a public method that can be accessed by the powerup game object:
Here we have the public method calling a coroutine in order for us to allow for a set duration of the powerup.
Finally we have the powerup script with a switch statement which is called when the collider enters the player: