Unity: Implementing degrading shields
To make our shield power-up a more interesting boost, we can make it a multi-level protection for the player. Here’s how we implement it.
The objective here is to give our shield 3 charges before it disappears and protect the player while active. Visually, we will fade the shield out with each hit.
First we will create a Shield.cs script and attach it to our shield object on the player:
The main part of the class is the SetShieldColor() method which takes an int and uses a switch statement to change the alpha channel.
In Start() we set the alpha to 1; the shield object is disabled by default so when the script is called the shield has been activated, which brings us on to the Player.cs script:
We add a reference to our Shield script and assign it in Start(). We also have an int to track the shield ‘charges’. Now when our shield is activated, we set the object to active and set the charges to 3.
Within the same script, our Damage() method now looks like this:
If our player takes damage while the shield is active, it will check the shield charges in the switch statement.
We increment the color, reduce the shield level by 1 and reset the damage delay (_playerDamagedTime) to ensure we don’t lose charges to quickly. Finally we return from the method at each stage to prevent the damage to the player until the shield is depleted.
And that’s it! We now have a shield that protects the player a bit longer, making it much more valuable to collect!