Switch Statements to the Rescue- Game Dev Series 19

Objective: Upgrade the modular from “if” to “switch”.

Previous: Creating Modular Powerups System

Although we have created a modular, the code is so nasty. It almost check every line when we collide with a powerup. What if we have tons of powerup, it would be completely nightmare in an if statement. Since we have powerup ID for our powerups, there is an efficient way to identify objects directly.

We can use switch statement instead of an if statement.

In switch statement, we can send in the value we want our switch to verify. Sort these value in separate cases and always end it with a break.
And there can also have a default to deal with the value is not listing in the cases, just like else in if statement.

As our modular, it can be changed like this,

In this statement, we simply told our Powerup script that if the ID is 0, switch to triple shot; if it is 1, give it a speed boost, and so on.
Switch statement will check the value we have imported and switch to the right one.

Then we should have the same result when we play it.

--

--

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
S.J. Jason Liu

S.J. Jason Liu

A passionate gamer whose goal is to work in video game development.