Switch Statements to the Rescue

If you have read my article from yesterday, you have probably observed that I have used switch statements instead of if-else statements on the power-up script.

Actually, it took me some time to get used to switch statements. You know, if you have taken a simple programming course, if-else statements are easy to understand and use. Thus, I was usually avoiding switch statements, as I was already getting the same result with the if-else statements.

Well, it turned out that I was missing an important knowledge.

First of all, I really had no idea that switch statements were more efficient than using if-else statements. Using switch statements also look nicer, and really easy to use. It is recommended to use switch statements rather than if-else statements if we have more than 2 conditions.

Switch statements also checks for a given condition for multiple values, just like If-else statements. Except from the difference that switch statements are only used for exact values rather than ranges, if-else and switch statements can be used for the same purpose.

Here is a statement with if-else statement:

As you can observe, this does not look much tidy. And it would be chaotic if we had tens of cases.

The logic to use switch condition is pretty straightforward:

First we state the name of the condition without the value after switch. After that, we state the case with the value for the condition. After typing in the action for the case, we end the case with break and continue with the other cases. Just like the else statement in the if-else statements, we end the switch statements with default line, stating the action to be helded if the statement results in a value different from the stated cases.

By using switch statements, we change the if-else statement given above as follows:

Looks more tidy, and it is really easier to read. It is better for us to get used to switch statements in the way of more efficient programming.

Unity Developer