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!

--

--

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