Unity Coding — Switch Statements

Christopher Graf
2 min readMay 25, 2021

--

As you advance as a Unity/Game Developer or any form of Programmer, your IF-ELSE statements are going to get longer and longer. While they work for almost everything you genuinely think to use them for, there is a cleaner and simpler way. Introducing switch statements.

Ok, maybe this picture is a bit harsh on IF-ELSE statements. There are actually a few things we need them for that we can’t do with switch statements, but let’s get back on point. Any time you have more than one else if and the separation is a single value, you should be using a switch statement.

Here’s an example. Say we have an int variable whose value determines our weapon. We can use a switch statement to use a different weapon based on that value.

Some things to make note of here. The switch statement begins with “switch” and in parenthesis the value you are checking. Like an IF statement, the rest is inside curly brackets. After each ‘case’ is the value you have a task for, followed by a colon.

After the colon you can add any code you want, but it MUST end with a break line. You will get an error if you don’t have one for any case, even the default. Default is written just by itself and acts the same as the ELSE. Purely there for if none of the other values are true.

If you go back now, you’ll most likely find many IF-ELSE statements that would be smoother as switch statements. You don’t have to change them all, but do remember for the future.

--

--

No responses yet