Shields!
Switch Statements To The Rescue

Our last powerup we want to add for our core game before moving on to User Interface is a shield. To create everything but the functionality for our new powerup, see yesterday’s article.
There is one slight problem though. In our Powerup script, we are now adding multiple if else statements in our OnTriggerEnter2D method. It’s okay to do, but it takes up a lot of space and becomes a bit messy to read. This is where switch statements can save us.
Switch statements allow us to take a variable, and run through the conditions of each value. If our _powerupID for our triple shot is 0. Case 0 will allow us to call a function for triple shot.

As you can see, things look a lot cleaner, and it is far nicer to add more cases as we add more powerups. Modular systems for the win! Switch statements also can have a default case for if a different value is entered.
Now let’s look at creating our shield.
First, create a public method in our Player script to match what we are calling in Case 2 above. We can then create a bool called _isShieldActive, by default it is set to false, but within our new method we can set it to active.
When the shield is active, we want the player to be able to take a hit from the enemy without losing a life. To achieve this, we can create an if statement in our TakeDamage method that when true, we set the bool back to false, and simply call return. This prevents us from continuing on with the TakeDamage method, thus not decreasing our lives count.
We have shield functionality, but we probably need some visual representation. In the Filebase asset pack, the shield sprite is animated. So much like our powerups we can create a simple animation cycle. If we add the shield as a child of our player, we can use scripting to turn it on and off, whilst it travels wherever the player moves.
We need to create a GameObject variable to store our shield, and in our Start method, we should confirm it is inactive using .SetActive(false);
Now in our ShieldActive method, we can change the value to true, turning our shield visual on. In our TakeDamage method we want to set it back to false.

With that, we now have three functional powerups in a modular system, ready for adding more further down the line. Next we need to add User Interface.
