Making a Modular Powerup System (featuring Enum Types!)

Blake Zoeckler
4 min readMay 9, 2021

--

A very important idea when writing code is the ability to reuse previous code that we have written. We don’t want to waste time constantly copying over the same code for new objects that are really similar to old ones. Whenever possible, it’s much better to adjust existing code so it can serve multiple purposes.

This new speed powerup is the perfect example to make use of this technique. Here I’ve set up all its necessary components in the inspector, including the same Powerup script that we had used for the triple shot. As it stands, doing this will cause it to act just like a triple shot powerup, allowing the player to shoot three lasers when collected. Let’s use some coding finesse to fix that.

Lets open the Powerup script and add a new variable that we can use to keep track of which type of powerup this is.

Now we can set an integer value in the inspector to keep track of powerup we are dealing with. Since this is a speed powerup, we set the Powerup ID to 1.

This is functional but has a big problem. It’s very easy to forget which number leads to which type of powerup. This can cause some headaches later if we aren’t careful. It’s a much better idea to use an Enum type instead. Enums are a list of identifiers that are assigned to numbers automatically. Here I’ve put the three types of powerups I want in a new enum called PowerType, and we can see that each one corresponds to a number value.

Now the inspector has a much more useful drop down menu that clearly shows what types of powerups are available.

Alright, so now it’s time to actually use this new Powerup ID to create speed behavior. Lets clean up some of the code in the Powerup script, and add in a way for it to know what to do depending on the type of powerup it is.

We compare the enum types either by converting them to integers, or by referencing the enum identifiers directly. Either way works.

Now we can modify the Player script so it knows what to do when StartSpeed is called. In this case, we would like to boost our speed from a measly 5, to a much more impressive 8.5 units per second.

We need to set up the StartSpeed method and EndSpeed coroutine that will cause the player to return back to normal speed.

Finally, we modify the player’s CalculateMovement method so it can determine how fast it should move. _useBoostSpeed determines whether it moves at the boosted speed or the normal one.

I’m using the “?” operator which acts like an if statement.

We are all done! Now the ships really zooms around after picking up the new powerup. It’s also going to be very easy to add yet another new powerup in the future.

--

--

Blake Zoeckler
Blake Zoeckler

Written by Blake Zoeckler

I’m a passionate and talented software engineer seeking an opportunity in game development.

No responses yet