Unity Game Development — Optimizing Code with Switch Statements
4 min readApr 12, 2021
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 a…