Shield Strength can take up to 3 hits before breaking

How to make your shield take 3 hits before setting the game object false.

I created previously this simple shield powerup which protects the player from one hit and disables after that. But what if we want it to protect us 3 times and then disable it?

If you want you can check this article where I wrote about the shield powerup.

Here is the shield and shiel UI in the left side, which shows us how many times we can get hit before our shield turns off.

Player Script

For this, we need to create a public void ShieldsActive()
We need to set our shield live and UI shield lives to 3 and we need to activate them too.

Player Script

We need to store our healthBar somewhere so we create a
public HealthBar healthBar;
And then in the Start() function we search our Healthbar component and set the health to 0.

HealthBar Script

In our HealthBar script, we need a slider thatwe manipulate from the player script.

Slider is one of the things we need for this script and an integer named shieldHealth

Then we need a way to set the max health

SetMaxHealth

And then we need a way to set the current health in the health bar

SetHealth

Now we can work on the code for our shield! :) We already have a Damage function inside the Player script. Now we need to check that if the shield is on and how many lives we have, then depending on those we minus from our HealthBar by using SetHealth(1);

  1. We check if the health is 3 and if our shield is on, then we minus 1 from our _shieldLives and SetHealth(2)
  2. Then we check if our _shieldLives is 2, and once again we minus 1 from the _shieldLives and SetHealth(1)
  3. When our _shieldLives is 1, we minus 1 from _shieldLives and SetHealth(0) and we set our shieldActive and our shield to false.

Our Damage code will always happen when our player gets hit. So we call this function every time the Player collides with the Enemy.
The return part will stop the code from continuing onwards.

Awesome! Our shield doesn’t break after one hit! :) We have a chance to fight against our enemies.

Thank you for reading!

Photo by Kylo on Unsplash

From the beautiful snowy country with a touch of "good" humor? Inspired Unity Developer to learn more.