Switch Statements to the Rescue

Jason Schneider
Jul 21, 2021

--

From my post on modular powerups, we have the below:

This shows us using if and else if statements to find which powerup has been activated, from three(3) powerup ID’s. What if we had 20 or more ID’s? Those else if statements would be rather long and cumbersome, a best practice method is to use a switch statement instead.

A Switch Statement is just like any other statement in Unity:

The statement “switch” followed by parenthesis which encompasses the variable; in this case powerupID; we want it to switch between.

A Switch Statement uses things called cases to differentiate between variables, such as:

break; just lets the code know that this is where that case finishes.

The first thing we can notice is that a Switch Statement is a lot more compact, and therefore going through the code of 20 or more cases will be far easier than the same amount of else if statements.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response