Project 1: Space Shooter

How to use switch statements

With an example of using power ups

Power ups activate as intended.

Previously I used the if- else statements to handle which power up the player had picked up. In my case there is nothing wrong with it, since I don’t have that many power ups and the decisions only call one activation method inside the Player script. But if I have to make more things happen at the time of collection or I have more power ups, this most likely will become quite cluttered and hard to read.

Because I use an ID to distinguish between the power ups, I can use that as a selector for a switch statement. Not only does this make the code easier to read, it also makes it easier to spot if every power up has its own logic. For comparison purposes here is the original implementation and further down the new one with the switch statement.

The original implementation with the if - else statements.

The way to use switch statements is simple. It asks for an input pattern which is compared with some expression chosen by the programmer. In my case the input pattern is simply the integer type power up ID, and the expressions with which it is compared to the integers , and, since I only have three power ups at the moment.

The new implementation with the switch statement.

If the power up ID matches with one of these, the code under that particular case is run. In my case if the _powerupID is , then case will be selected and the speed boost is activated for the player. The break statement at the end of all the cases ends the execution of the switch statement.

Last thing to note is the default case, if no other case evaluates true, then this case will be executed. It doesn’t matter where it is defined inside the switch statement, that is whether it is the first one, the last one or one in between, it will always be the last one executed. It can be used as an indicator that something went wrong, in my case the ID would be something else than it is supposed to be, or it can be used to do whatever the programmer wants it to do. If there is no need for the default case, it can be omitted.

--

--

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
Eero Saarinen

Eero Saarinen

Unity game developer in the making.