Switch Statements to the Rescue!

Objective: To tidy up our modular powerup script from if else statements to a switch statement!

Now that we have created our modular powerup system script, you could probably imagine that what if we had 20, 30 or 50 powerups in our game and we had to write an if else statement for each one? This would not only become quite tiresome, but the code itself would look quite big and clunky and not very appealing on the eyes for team members who could be looking to revise the code. So let’s have a look at tidying up this modular powerup system with a switch statement!

What is a Switch Statement?

A switch statement evaluates an expression (or variable), which then compares its value to values of each case and when it finds it’s matching partner it executes the code within that case before breaking out.

An example of how this looks like:switch(powerupID)
{
case 0:
player.TripleShotActive();
Destroy(this.gameobject);
break;
case 1:
player.SpeedBoostActive();
Destroy(this.gameobject);
break;
default:
Debug.Log("Unknown number");
break;
}

E.g. Here, we are evaluating the variable ‘powerupID’, now when the powerupID returns a 0, it will then run through the cases in an attempt to match. In this case it will find case 0 and it will execute the code within before breaking out of the switch statement.
If our
powerupID was to return a number that was outside case 0 and 1 (say 15), then it would execute the default case and let us know in the Console window that we have an “Unknown number” before breaking out again.

Let’s have a quick look at our original code so we know what we are working with and what is going to be changed. Below you can see our if-else statements:

As you can see it is a bit of an eye sore, so let’s switch this whole thing up!

Here we are keeping the same if statement, where when we collide, If the other.tag is “Player”, then we are going to switch through the powerupID variable and depending on which number it is, it will reflect the corresponding case number. E.g. If we collect the Triple Shot Powerup which we have previously given a powerupID value of 0 in the Inspector, then this will correspond to case 0 and as such run the method contained within.

It will then break out of the switch statement as we have completed it. It will then run again when we collide with another powerup. If the powerupID numbers are not 0, 1 or 2 at this time, then we have a default option at the bottom which is going to give us a Debug.Log in the Console window to let us know.

--

--

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