Step 10 — Shields and Switch Statements

The last powerup we will give the player is a shield via powerup.

Wubwubwubwubwub

So once again, same deal with creating the Shield powerup object. Rigidbody. Collider. Script.

On the Player object, attach a Shield sprite to it as a child object. We will enable the visuals of activating the shield by enabling/disabling this Shield sprite object. On the Player script, we shall add a Serialized GameObject field to refer to this Shield sprite object.

Player script

When the player’s ShieldPowerupActivate() is called, the _isShieldPowerupActive bool is set to true, and the Shield sprite visual is activated and will be seen in-game. Then when the player takes one hit, the bool is set to false, and the shield visual turned off, but the player won’t take damage in that collision.

On the Powerup script, we face a bit of an inconvenience. We could just add another else if to the OnTriggerEnter2D method but then it starts to look messy.

This is just for three power ups. What if we had five, or ten? It’d be a long list of if-elses.

A way to clean this up is to use switch statements instead.

The switch looks at the variable, in this case _powerupID, and enters a case that matches the value. It then executes the code block of that case until it hits a break, which moves the logic out of the switch to the final step of destroying the Powerup object. This break is very important otherwise the code continues to “fall through” the other cases on its way down. If the _powerupID doesn’t match any of the cases it executes the default code block.

Switch statements are a much cleaner alternative to if-else and should be used if there’s at least three conditions to an if-else.