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!




Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Configure Composer to use Nexus

Linux Permission and User Management [chmod and useradd]

Frequency-Power and Voltage-Reactive Power Characteristics of a Synchronous Generator — The…

Manage Cloud DB via Cloud Function

What Makes Optimizing SaaS App Performance Special

How did Reactive Programming helped to build High Throughput and Low Latency based Software System

Ever since I was a little boy, I have only ever wanted to be a Doctor.

Why Do Organizations Scale So Poorly?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ryan McCoach

Ryan McCoach

More from Medium

Switch Statements to the Rescue

Mastering Unity Scripting | Summary — Chapter 1: Unity C# Refresher

Making Moving Platforms In A Unity Platformer

Day 96: How To Upgrade Your Project to URP in Unity