Switch Statements to the Rescue

Objective: Cut out several if and else if statements with a Switch Statement!

Natalia DaLomba
1 min readMay 20, 2023

Begin writing a switch statement by writing the keyword switch, then encased with the int _powerUpID so we can perform different actions based on what the ID is.

We currently have 3 _powerUpIDs (0, 1, and 2), which are called cases in a switch statement. In each case, we write the code we want to be executed followed by the keyword break to break out of the switch statement.

There’s also a default case that if there’s a _powerUpID passed through that is not 0, 1 or 2, it will perform specific code in that case.

switch(_powerUpID) {
case 0:
player.TripleShotActive();
break;
case 1:
Debug.Log("Collected Speed PowerUp");
break;
case 2:
Debug.Log("Collected Shield PowerUp");
break;
default:
Debug.Log("Invalid PowerUp ID");
break;
}

The outcome is the game accomplishes what it did before but now it’s more efficient code and much easier to read.

--

--

Natalia DaLomba

A Unity C# developer inspired by game design logic used to create digital adventures. https://www.starforce.games/devlog/