Journal 20 — Switch Statements in Unity Game Practice
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.
Instead of an If statement, we can use the switch format and define each case.
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.
We will take the same If-Else If statements and convert them to switch statements.
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.
Here I have inserted switch statements but kept the If-Else If statements for comparison. When running, both statements work the same.
Thank you for stopping by!