Member-only story
Unity Game Development — Optimizing Code with Switch Statements

Previously, I worked on a script to create modular power-ups. The code uses conditional statements to control which type of power-up the player collects. If we decide to add more and more types of player upgrades, this code will get long and messy.
Enter the switch()
statement.
The switch statement is a selection statement that chooses a single switch section to execute from a list of candidates based on a pattern match with the match expression.
To illustrate this definition better, take a look at the following syntax.

- This variable can be any non-null expression. I’m using an int for the example.
- The syntax for this statement begins with the keyword:
switch()
. - The expression to be evaluated by the switch statement goes inside the parenthesis.
- Using the
case
keyword, we add potential candidates followed by a Colon (:). The candidates have to match the Type of expression that the switch statement is evaluating. When the evaluation finds a match, it executes the code block that follows it. Every case must end with abreak;
keyword. - The
default
keyword executes code if it does not find other matches.
Armed with this knowledge, I’ll make some changes to the power-up code I created previously. I will also add a third power-up called Shields.
Currently, my power-up behaves like this:

Now that I want to add a third option to my list, I could add another else if()
statement checking for if PType == 2
. But when evaluating a single condition, the switch()
method is often a better choice.
To change our code, all we have to do is the following.