Switch Statements in Unity: GameDev Journey 09

Brett Blandford
2 min readMay 21, 2021

Today I learned about switch statements while implementing my third power up, the player shield. I set up a a Shield power up prefab just like the others, and gave it a powerUpID of 2 (see last article for more info). I added another else if statement in my collision detection which looked like this:

Little did I know there is a a cleaner way to achieve the same thing using a switch statement. Switch statements are helpful when you are comparing the same variable against different values over and over again. In this case, the variable we are comparing is powerUpID. The following picture is how these series of if statements can be changed to a switch statement:

powerUpID goes inside the parenthesis because it is the variable we are comparing. “case 0:” means run this code when powerUpID = 0, “case 1:” is means run this code when powerUp ID = 1 and so forth.

You can look at “break” as a closing bracket in an if statement. It basically this is the end of what needs to be done within this case. On the same note, you can look at the “default:” statement as an else statement, meaning if none of the other cases are true, the default statement will be chosen.

The switch statement may just seem like a fancy way of doing if statements, but it can make your code cleaner and more understandable when you are comparing the same variable over and over again.

End of Game Dev Journey 9!

--

--