Creating Modular Powerup Systems
Objective: Create a second power up and make the system modular.
Firstly we’ll create a speed powerup just like with the previous one. So drag the speed powerup sprite into the hierarchy, rename it, set the sorting layer, add a 2D box collider and rigidbody, set the sprite size(scale), set it as a trigger and remove the gravity. Once everything is set, make it a prefab.
To change the powerup script to make it a modular system, start by creating a serialized private int called powerupID. Add the powerup script to the new speed powerup prefab. Click on the triple shot powerup prefab and assign 0 to the powerupID and then assign 1 on the speed powerup prefab.
In the powerup script go to the on trigger enter method and add an if statement within the player not null check. If powerup is 0 run the triple shot active as already implemented, if 1 we’ll just debug log “speed collected” and if 2 (future powerup), debug log “not triple or speed” for now.
Now to get it working quickly to test, go to the spawn manager script and create a new serialized game object called speed powerup prefab then within the spawn powerup method, inside the while loop create an integer variable called powerup and set it to a random number between 0 and 2. Then create an if statement to instantiate the right powerup based on the random number.
Next we’ll work on the speed powerup functionality. Go to the player script and along with the speed variable, we can add a speed multiplier. Then add a private bool to check if the speed powerup is active and set it to false as a default. Inside the calculate movement method, add an if statement to check if the speed powerup is active and if so add the speed multiplier to the speed calculations and if not use the already defined calculations.
Like with the triple shot powerup, we need to create a public speed powerup activate method that can be called from the powerup on collection and create a coroutine to deactivate the powerup after 5 seconds.
Now that we have the functionality set up, go back to the powerup script and swap the debug log to the speed activate call.
In the next post, we’ll do some code optimization on the powerups logic and implementation.