Unity Dev Blog: Creating Modular Systems

Michael Hatfield
3 min readApr 22, 2022

--

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

--

--

Michael Hatfield
Michael Hatfield

Written by Michael Hatfield

IT Specialist / Indie game developer

No responses yet