Simplify Your Code With a Switch Statement

Andrea Zilio
2 min readApr 24, 2021

This has been a heavy week working on some really exiting projects. :D
So it’s just a short one today…

In games we often need to check for a number of values. The code can quickly become hard to read if we don’t optimize it.

An example from the Space Shooter game we looked at before. Let’s say we give our player different enhanced abilities, which we call power up. One is a triple shot, one a speed boost and the third one a shield. The player can collect them while playing. To test which power up the player collected and thereby needs to be executed, the obvious way is to add a series of if and if else statements.

While this works, it becomes cumbersome when we have a large number of options. Imagine having 50 if and if else statements in your script!

An easier way to do this, is to use a switch statement. We simply define the variable we want the switch to check for and then define the different cases with instructions for each case.

It does look neat, doesn’t it?

What if we get a value that has not been defined? We can add a default case which is automatically applied if the value is not defined.

Give it a try!

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

Andrea Zilio
Andrea Zilio

Written by Andrea Zilio

Passionate Game Developer and Learning Expert. I love to create games and interactive experiences using Unity, Articulate, C#, JavaScript, PHP, HTML, CSS.

No responses yet

Write a response