Making the Shield More Powerful
Now it is time to make the shield a little more powerful by giving it the ability to take 3 hits. To do this you will need a variable to keep track of how many hits the shield has left and when that points to the sprite renderer for the shield so that you can adjust the color of the shield as it takes hits. Create these at the top of the class with the other variables.
private int _shieldHitsLeft;
private SpriteRenderer _shieldSpriteRenderer;
Next, in the start function initialize the variables.
_shieldHitsLeft = 0;
_shieldSpriteRenderer =
_shieldVisualizer.GetComponent<SpriteRenderer>();
if (_shieldSpriteRenderer == null)
{
Debug.LogError("The Shield Sprite Renderer is NULL.");
}
Next, update the ShieldActive function. Set shield hits left to 3. Adjust the scale of the transform so it is slightly bigger than normal. As the shield takes hits it will decrease back to its normal size. Set the sprite renderer of the shields color to something bright like white so it stands out when it is at full power.
public void ShieldActive()
{
_isShieldActive = true;
_shieldHitsLeft = 3;
_shieldVisualizer.SetActive(true);
_shieldVisualizer.transform.localScale = new Vector3(2.3f,
2.3f, 2f);
_shieldSpriteRenderer.color = Color.white;
}
Last, you need to update in the Damage function where it checks if the shield is active. When the shield takes a hit you want to decrease the number of hits left. Then add a switch statement to handle the different scenarios for the number of hits it has left. As it has less hits left you want to reduce the scale of the shield visualizers transform and also change the color to show that it is not as powerful.
if (_isShieldActive)
{
_shieldHitsLeft--;
switch (_shieldHitsLeft)
{
case 2:
_shieldVisualizer.transform.localScale = new Vector3(2.3f,
2f, 2f);
_shieldSpriteRenderer.color = Color.green;
break;
case 1:
_shieldVisualizer.transform.localScale = new Vector3(2f,
2f, 2f);
_shieldSpriteRenderer.color = Color.blue;
break;
case 0:
_isShieldActive = false;
_shieldVisualizer.SetActive(false);
break;
}
return;
}
That’s it! Now when the shield takes a hit it lose power until it is gone.
Good Luck Adventurer!
-Chris