Michael Davis

Apr 13, 2021

3 min read

Switch Statements: An Elegant Tool for a More Civilized Age

Still from Star Wars, Luke turns on a light saber for the first time. Obi Wan watches.
How it feels to learn about switch statements for the first time.

In the previous article I created a modular powerup system based on a series of if/else if checks against the powerup’s ID number. This is fine for three powerups. But what if I decide I need three more? A dozen more? Billions more?

Okay, maybe not billions.

There’s a slightly less text intensive way to sort out any number of powerups: the switch statement. Let’s take a look at the two side by side.

At a glance, the anatomy of a switch statement is similar to the if/else if. It’s a bit more streamlined though, in terms of expandability and readability. To expand the number of powerups all we need to do is add a new case and link it to the proper method in the Player script. No need to retype the _powerupID variable in each check.

Here’s a rundown of the rules of switch statements:

  • The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type.
  • You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.
  • The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal.
  • When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
  • When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
  • Not every case needs to contain a break. If no break appears, then it will raise a compile time error.
  • A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true.

That about covers it. We’re now well equipped to tackle even more complex things now that we have the help of switch statements. Join me next time, and we’ll talk about the ease of building UI elements in Unity.