A Well Oiled Machine — Modular Systems in Unity

It’s time to expand upon the powerup system, but rather than utilize repeating “if” statements, we can deviate to a switch statement.

A switch statement is used to hold lists of possible outcomes efficiently. In the case of the powerup system, a switch will let us make 5, 10, or 100 powerups with relative ease.

Switch statements are started by using the keyword “switch”.

Inside of the parentheses we can identify a variable that we want to switch between. I made a new variable: powerUpID.

Now switch statements are full of cases. Cases are the logic that will run for each possible outcome of the switch statement. An easy example you could use this for would be a treasure chest with 5 possible items inside of it. You could use a switch statement and make a case for each of the five items, then have one selected by a random range value.

Here is what a singular case looks like:

All switch cases must have a “break”.

This is the diction that tells the statement that the case’s logic is over and it can then receive more cases, or that the entire switch statement is done.

Cases start on 0, so the third possible outcome is actually case 2. Right now, case 2 is just a placeholder for future logic, but we could keep making more cases by continuing the pattern.

Case 1 is running a new function from the player script that speeds up the player for 7 seconds when they collect a new powerup. It was implemented the same way as the triple shot (see previous articles).

Another modular system to inspect are arrays. Arrays are variables that can hold multiple values. This is very useful for our spawn manager, as we can make a new variable of type Gameobject and make it an array named powerups;

When you make an array (and it is public) you can edit it in Unity!

Finally, let’s change the spawning logic so we don’t just get triple shot powerups.

I set a new integer variable inside of the SpawnPowerup coroutine named “randomPowerup”. This is set to a random range between 0 and 2.

NOTE: When using random range for arrays, you need always have the higher value be 1 more than the possible outcomes. In this example, only two possibilities can ever spawn.

Then, I instantiate a new gameobject (newPowerup) that is grabbing the randomly selected powerup, and finally placing it inside of a container for organization.

Let’s see it in action!



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
Jack Leavey

Jack Leavey

I am a software engineer with years of experience branching into game development, specifically in Unity. Follow along for guides on creating game mechanics!