Switch Statements to the Rescue

The script below shows a CONDITIONAL checking the _powerUpID of the powerUP the player just collected using a few IF, ELSE IF statements. There is nothing wrong with this, but if I were to add another 5 or 10 powerUps, this method may not be the most optimized ways of checking the _powerUpID.

Without a Switch Statement

Enter Switch Statements. Switch Statements are great if you are using a bunch of ELSE IF statements to check the same condition for a different response, such as the _powerUpID, but you want to tidy up the code to make it easier to read and more efficient.

Switch Statements are just like ELSE IF statements, in that, they check a condition against multiple values. We type switch followed by the CONDITION you are checking, which in this example is our _powerUpID. Switch Statements use cases, instead of an IF (CONDITION == VALUE). The case is followed by the value you are checking and for the PowerUpIDs that would be case 0, 1 & 2. With each case, you will want to follow it with what you the code to execute if that case value is returned, just like THEN in a IF THEN statement. For the PowerUpID Switch Statement the following with being executed.

case 0 = Triple Shot Power Up

case 1 = Speed Boast Power Up

case 2 = Shields Power Up

With Switch Statement

After each method, you need to add a break line to let the Switch know that the code is done executing. Adding a default case at the end to help you debug, just in case you return a value you were not expecting. Now, look at how nice and neat that code is…Thank you Switch Statements!