Unity Game Development — Optimizing Code with Switch Statements

Claudio Grassi
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.

  1. This variable can be any non-null expression. I’m using an int for the example.
  2. The syntax for this statement begins with the keyword: switch().
  3. The expression to be evaluated by the switch statement goes inside the parenthesis.
  4. 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

--

--

Claudio Grassi
Claudio Grassi

Written by Claudio Grassi

Experienced digital artist, Unity game developer & coder with a knack for problem solving and a passion for video games.

No responses yet