Switch Statements

So, you’re adding power ups to your game and you’re using a modular approach to streamline your project. So, in your Power Up script, you’re checking for the power up ID to determine which power up method to activate on the player. With one or two, it’s no big deal … but what if you are adding a third or fourth or tenth power up?

Example of else if statement with 3 different power up IDs

You probably don’t want to keep using else-if statements over and over. They take up quite a few lines and they are not the easiest to read and follow. So, what other options are there?

Enter Switch Statements

Switch statements can replace repetitive else-if statements when each else-if condition is checking the same variable for a different value.

This else-if statement cannot be replaced with a switch statement

Switch statements work when conditions are mutually exclusive, like in the case of power up IDs. When it’s 1, do this; when it’s 2, do that; etc. Since the example above checks a different variable in the second condition, this is not eligible for a switch statement.

Outline of Switch Statement syntax

Instead of listing each condition as “variable equals A”, switch statements allow you to specify the variable once in the switch statement at the top of the code block. Then, identify the value of the variable in each case. If you need to execute a block of code when the variable value does not match a specified case, you can add a default case at the end of code block.

You probably noticed the break at the end of each case — this is what tells the computer to stop processing code and exit the switch statement. Otherwise, the computer would continue to evaluate whether or not the variable matched any remaining cases, including the default case. Don’t forget to break!

Example of else if statement with 3 different power up IDs

If we update the collision method in the power up script, we can replace the else-if statement with a switch statement — which is much easier to read and will be easier to add to as we add more power ups.

Play-testing shield power up with switch statement

Switch full power to shields!