In a previous article, I went through the steps involved in creating a powerup for our Player’s weapon systems. It was, however, a very inefficient method due to it not being very flexible or adaptable. By this, I mean that we would need to create a new script for each new powerup we create.
In this article, I’m going to look at modifying our existing scripts to enable us to create new powerups for the Player without the need for any new scripts. This will require some thought into what powerups you may add to your game and some changes to the structure of our code to enable that flexibility.
NOTE : As with all things in coding, there are many ways to get the desired result. This article demonstrates one method of achieving this by way of the Player script managing everything and keeping the powerup script very simple.
Let’s look at adding a speed boost :-
Firstly, let’s add the functionality of a speed boost to our Player script —
With these few lines of code our Player is ready to use a Speed Boost powerup but there is still more to do (see my last article for setting up the animated visuals for the powerup).
In order to have the same powerup script be used for all our powerups, we need to modify the manner in which we activate the different powerups.
To be able to differentiate between different powerups using the same script, we need to add an identifiable reference (an ID), each powerup could also have a different duration and each may add a set bonus effect. In this vain, we need to add some variables to our powerup script (we already had the speed variable for governing how fast the powerup falls down the screen)—
Back to the Player script, we need to add some code to filter through and find out which powerup just got collected rather than calling a specific powerup method from the powerup script —
Destroying the powerup here, after checking if the powerup is already active, means we only ‘pick up’ the powerup if we can activate it.
As we have passed all the relevant information for the powerup that was collected, let’s make use of it by adapting our powerup activation methods —
And a final change to make sure the variables are passed into the above methods —
Activating powerups in this manner allows us to only need to add functionality to the Player without requiring to add new scripts for each new powerup. Plug ’n’ Play powerups if you will…
NOTE: Just because the information is given, doesn’t mean it has to be used — i.e. the bonus variable isn’t used for the TripleShot powerup as that only switches on/off