Switching over to cleaner code — A quick tip on switch statements and why you should use them.

You have 15 different powerups in your game. Do you really want 15 if/else statements?

When you want to add another powerup in you have to go back and edit your else statements, cutting, and moving code. This is where switch statements come in.

Switch statements are tidier, more performant, and are easier to read. They are also very easy to expand upon. They are called by using the keyword “switch” and passing in a parameter to check.

You can then provide a “case” which is what we check against the switch statement parameter. If there's a match we run the code under our case statement. To end a case we use the keyword “break” before adding our next case.

We also have a default case that is called if we do not get a match (similar to our else in an “if” statement”

Now let's show how easy it is to add a new check to a switch statement.

And as we can see our powerups still work as expected

That’s all for now.

--

--

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
Luke Duckett

Luke Duckett

Unity developer with a love of learning all things programming.