Cleaner code with switch statements

Niklas Bergstrand
3 min readApr 5, 2021

There is nothing wrong with using if statements, but when you have a lot of them checking the same condition, the code can look a bit messy. To make it much cleaner, we can use switch statements instead. We will use a switch statement when adding the third and final power-up, the Shield.

In order to set up the third power-up, we can follow my articles for setting up the first power-up here and the second power-up here. After the third power-up has been set up, we need to increase the array on the SpawnManager and add the Shield power-up:

Set the power-up type to Shield:

Remember to increase the random number before the power-ups are instantiated:

Add a bool to check, if the Shield power-up is active. We also need to add the function to activate the power-up:

Now it’s time to replace the if statements for the switch statement. With a switch statement you check one condition and then jump to the corresponding case. Each case must finish with a break to tell the program that it has reached the end of this call. As you can see on the screenshot at the beginning of this article, there is also the default case which you can add to capture a condition not listed on a case:

Add a GameObject to the Player script that will hold the visualization of the shield. Inside the DamagePlayer function add an if statement to check if the shield is enabled and if so, do not remove a life and turn off the shield:

Drag in the sprite for the shield and animate the same way as the power-ups. Add the shield as a child to the player to ensure that it will move together with the player object and reset the position. Lastly, add the shield to the Player script:

Set the order in the layer to be higher than the player to ensure that the shield is rendered over the player object, and then disable the game object:

Final result:

Good luck!

--

--