Too many ifs? Lets switch that!

If if if if if if if if this if that if else… It can be really easy to get caught up in using too many if statements in your code. There can be so many decisions to be made in a game if the player does one of a thousand things. Thankfully there is an alternative way and it is in what is called a “switch” statement.

Previously in my code for my Powerups, I was using an if statement to check what Powerup ID the powerup had to determine what it would do.

However, using the much cleaner “switch” statement, we can break it down between cases. By telling the switch statement that each case# is a PowerupID, we have just easily linked it up to a variable to determine what the powerup is. So here, I have IDs 0–2 and each have their own respective code instructions.

Much cleaner, easier to look at, and easier to add on to!

I would say if you have more than 2 or 3 if statements in a set, a switch would be the way to go. I am going to have quite the number of powerups by the end so better to do this earlier than later!

See you on the next post!

--

--

--

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

Recommended from Medium

Elon Musk: Can we have a special SpaceX-edition Tesla Model 3, please?

Making slides from anywhere for anyone using Marp, GitLab Pages and Gitpod

Optimizing Complex Data Distribution in MaxCompute

Web Worker and Dart #2

Apache Spark On Kubernetes and Spark Security

How to Set Up VMware Workstation Server: An Expert Guide

CHI (氣): The Easiest Way To Track Your Codebase Health

THE BENEFITS OF PREDICTIVE ASSET ANALYTICS IN THE UTILITIES INDUSTRY

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
Edward Kim

Edward Kim

More from Medium

Free Refills Included — Adding a Power Up to Replenish Ammo

Unity use right stick to aim in 2D with new input system

Importance of Being Organized in Game Development

Using Reflection Probes To Improve Game Visuals