Switching it Up — Switch Statements in Unity
Since we plan on having more than one power-up, it’s a good time to explore the use of a switch statement instead of our If/Else statements.
What is a Switch Statement and how does it differ from an If/Else?
The main difference is that an if/else can be used for making decisions based the parameters that it’s evaluating and a switch checks against a single variable per case (with the ability of having many cases). So clearly they have their uses in the right circumstances.
How to use a Switch Statement
For our Space Shooter game we swap out our if statement to check against which Powerup the player object has collided with. We call the switch statement and point it to out _powerupID variable ease case corresponds to one of the powerups and we call to the appropriate method to invoke it from the player script. at the end of each case we call a break; and finish our switch with default case as good code hygiene. That’s all there is to it. Now our powerups are starting to take shape. We’ll program the behaviour of our shields next.