I kinda fell in love with switch statements as soon as I was taught them. I try to use them in place of if, else-if, and else statements as much as I can, which is generally until I need to check whether something is greater or less than another value or when I need to check multiple conditions (e.g. ‘if (!gameFinished && !gamePaused)’). I’ve been told they’re more efficient (although I won’t pretend to fully understand how), but ultimately I just find them tidier and more readable. I can very quickly read the entire statement and know exactly what eventualities or ‘cases’ I’m accommodating. As an example, here’s a snippet from the 2D Space Shooter I’ve been working on to determine which power-up logic should be called:
Here, I’m taking the string variable ‘powerupName’ and checking it against a number of cases or possible values I’ve defined (‘Triple_Shot’, ‘Speed’, and ‘Shield’). If the value of ‘powerupName’ is equivalent to any of those case the logic between the appropriate case line and ‘break’ line will run. The ‘break’ keyword (which is a syntax requirement) breaks us out of the switch statement once it’s been called, preventing any additional logic within the statement from running. If the value of ‘powerupName’ does not match any of theses cases then the ‘default’ case will be run (which is generally where I’ll put in a Debug.LogError saying ‘Case not recognised’).
Admittedly, I don’t particularly recommend doing what I’m doing here by comparing strings, just because there could well be a chance that the switch statement receives a misspelt value like ‘TripleShot’ instead of ‘Triple_Shot’. I’d recommend using an enum or integer value instead to get around this, but in my case I can be reasonably sure the spellings will be correct (as the string passed into this method is in fact an enum converted into a string using the ToString method).
Appreciate my slightly dry coverage of switch statements is unlikely to sell them all that well, but I really struggle to overstate how useful I’ve found these in making my code a bit more modular. I’m almost always using switch statements in combination with enums so that I can trigger different behaviours for different instances of the same class (e.g. a ‘red’ enemy’s behaviour as opposed to a ‘blue’ enemy’s behaviour). We can technically use if and else if statements to achieve the same, but these switch statements really do a great job at keeping things as readable and efficient as we can :)