Unity Dev Blog: Creating Modular Systems

Making your code do double (or triple) duty.

We could very easily create a script for each new power-up we make. The player will never see these scripts and would not know if we had 1 script to handle all power-up behaviors or 500 scripts. And while the player is important, let’s do something just for us today. We’ve worked hard creating that triple shot power-up system. So now let’s work smart and reuse what we can.

If all we do is attach the power-up script we wrote for the triple shot to the speed power-up game object, it will already move down the screen when it is spawned. The code is in there to make the game object move downwards. Unity does not know or care that it represents a different object! As is, it will act exactly as the triple-shot. Which is not what we want, but until we code in a way to distinguish between the power-ups, that is what we will get.

Regardless of the type of power-up, we want it to move down the screen and go away at the bottom if it is not collected by the player. So, the movement code is good as it is:

What is the next step? Well we need to create the coding to which power-up it is so that we know what fantastical powers to give the player. A simple way to do this is to assign each type of power-up a number or ID. Let’s say 0 for triple shot, 1 for speed booster, and 2 for shields.

Great! Now we can set the Powerup ID in the prefabs for each power-up:

And now we can test it…

Perfect! And all in one script. Easy to make changes, easy to debug.

But what if we add more power-ups?? We could keep adding if statements to our script but that could get messy and inefficient. Instead, tomorrow, I will cover using the Switch for situations like this one.

See you there!

1

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Michael Hatfield

Michael Hatfield

Math and science teacher / self-taught programmer and Unity game developer working hard to get into the game development industry fulltime.