Switch Statements in Unity

Bradley Yachimowski
2 min readApr 25, 2021

--

In Unity, we often use the “if” statement in conjunction with the “if else” when we have more than one possible condition. The “if” statement checks a condition, if true, it executes the instructions within its body or between the “{ }” brackets. If the next statement is another “if” statement, it to will be checked, however, if it is an “else if” statement it will only execute if the previous “if”, or “else if” statement was false. This can save execution time by not having to check the additional “if” statements. This works fine, but there is another solution.

The “switch” statement functions like the “if” and “else if” statements but is structured differently. The “switch” statement has only one set of “{ }” brackets that contain all of the possible conditions. Each condition or “case” is terminated by a “break”, “goto” or “return”. The “switch” statement has a “default” component that can be used to catch errors or assign a special action to prompt the user to make a valid selection. When the “case” is determined to be true, it will execute the code following the “:” and terminate the “switch” statement at the “break”. The “switch” statement can also use the “goto” statement to set up a mini “State Machine” within the body of the “switch” statement, for example, “case 2:” is true, instead of a “break” and the end of “case 2:” we can use “goto 1:” to execute “case 1:". “Case 1:” is executed and the “switch” statement terminates at the next “break”. In addition to “break” and “goto,” you can use a “return” to pass a value out of the selected case. Using “return” from within a switch can make the program hard to follow. It is best to assign the value to a variable of proper scope within the “case” then use a “break”. The nesting of “switch” statements is allowed but can make the program hard to follow and should be avoided. So you can see how the “switch” statement can have an advantage over the “if”, “else if” methodology. So now it's time to make a “switch”, and make your program easier to follow …

--

--

No responses yet