Creating Modular Powerup Systems

Objective: Create a modular powerup system and create a speed boost powerup to give the player movement speed when the boost is active.

The first thing we need to do is create a variable to assign and store an object’s ID.

private int _powerupID

We can now assign the ID’s value in the Unity Inspector:

Set the triple shot powerup’s ID to 0.

triple shot powerup ID = 0

Set the speed boost powerup’s to 1.

speed boost powerup ID = 1

This ID will make storing future powerups easy and organized. Instead of using if statements to call the powerup ID variable every time, which will lead to very unorganized code, We can actually use:

Switch()

Switch statements allow you to switch through a variable and call the ID of the powerup we want to use.

switch (_powerupID)

With this new system, let’s go ahead and actually implement the next powerup, the speed boost powerup. We will need two variables for the speed boost to work:

The top variable will tell the player whether the speed boost is active. The bottom variable will be how much speed the boost will give the player.

Now to set the behavior of the speed boost powerup:

When SpeedBoostActive is called, it will set the _isSpeedBoostActive to true. The SpeedBoostPowerDownRoutine is what will dictate when the powerup will end.

If the speed boost is not active, the player will move at their normal movement speed. If the speed boost is active, the player will move at their normal speed with the speed boost value-added to it. When the powerup timer has ended, the boost speed is subtracted from the normal movement speed.

The last thing we will do is make a random powerup spawn. To do this, we need to use an array:

_powerups array

The [] is what makes the variable an array. Think of an array as a fixed list, and in this case, you can think of it as a fixed list of powerups.

And now we can add the powerups to the list in the inspector:

0 is our triple shot, and 1 is the speed powerup. We will leave the 3rd spot open for a later shield powerup.

Every 5 to 8 seconds, a random number between 0 and 2 will be chosen (0 is inclusive and 2 is exclusive). The powerup assigned to that random number will be the one spawned in.

Learning to become a unity game developer