Journal 20 — Switch Statements in Unity Game Practice

Chris Nielsen
3 min readMay 2, 2021

--

After practicing on several scenarios using If and If-Else IF statements, we will now introduce the use of switch statements. Switch statements can be useful if you have several potential options that are defined for a particular variable, and you have different instructions for each option to execute. For additional information, you can refer to these two links from Unity and Microsoft:

Working with Switch Statements — Unity Learn

C# switch statement | Microsoft Docs

In the previous example on using multiple power ups, we worked on expanding power ups to three options.

Powerup script, create an ID associated with each power up

Instead of an If statement, we can use the switch format and define each case.

Powerup script, fill in switch statement with different conditions (use comments or Debug.Log statements if there are certain conditions that are not completed)
Powerup script, switch statement completed for three power ups
Unity Playmode, switch statement changes powerups accurately

In this example, we have set up identifiers for specific levels of difficulty, and we will generate a random number to output a message on the level difficulty, and we can press the space bar to get a new random number during gameplay.

C# example, difficulty level assigned
C# example, send message to console on results of difficulty level

We will take the same If-Else If statements and convert them to switch statements.

C# example, switch statement inserted

And as you see in these results in the Unity console, I kept both the If-Else and switch statements active, and they both work the same.

In another example, we can use the keyboard to modify points and output messages on the points status.

C# example, points assigned based on pressing keys

Here I have inserted switch statements but kept the If-Else If statements for comparison. When running, both statements work the same.

C# example with If-Else If and switch statements side by side

Thank you for stopping by!

--

--

Chris Nielsen
Chris Nielsen

Written by Chris Nielsen

An Engineering Manager consultant who is seeking additional skills using Unity 3D for game and application development.

No responses yet