Switch Statements to the Rescue

Using switch statement to evaluate different cases according to a variable value

Rusben Guzman
2 min readJun 9, 2021

Objective: Improve the code of the modular powerup system changing the if statement for a switch statement.

In my last article I created a modular powerup system adding a new variable powerupID to the powerup script and checking in the OnTriggerEnter2D function for every case of the powerupID.

We can improve this code by using the switch statement. The general rule is if you have to create more than 2 if statements to check the value of the same variable you can change it to a switch statement.

The switch statement receives a variable and creates cases for every value that we need to evaluate for it. Every case has to end with the keyword break which indicates that the case ended. Finally we can add a default case to do something if any case matches with the current value of the variable.

So in the code above in each case we activate the respective powerup and in the default case we print a message in the console. As a result we have the same functionality but a better and cleaner code.

--

--

Rusben Guzman

A Software Engineer passionate about game dev and interactive products with Unity. I consider video games to be the artistic expression of programming.