Shield Durability

How to change color of Shield from script

Tristan Engel
2 min readJun 26, 2021

In this article we change the Shield to take 3 hits before it breaks. First we got the logic part in the script. Next we change the VFX of the Shield. The color will change based on the value of shield health. Finally we will add a visual indication just like our health UI display.

Script — 3 hits before shield breaks

Pseudocode

if shield power up is picked up
then set shieldhealth to 3
then activate shield and update shield vfx
if damaged and shield is active
then shieldhealth —
then update shield vfx
if shieldhealth == 0
then deactive shield

Actual Code

Shield part of on Damage() method. If Shield isn’t activated then player is damaged normally.

if (_isShieldActive == true)
{
_shieldHealth--;
if (_shieldHealth <= 0)
{
//deactivate shield gameobject
_shield.SetActive(false);
_isShieldActive = false;
//exit function with return
return;
}
else
{
//TODO UpdateShieldVisual
}
}

Method that activates the shield. (Other powerup cases are removed here)

public void PowerUpPickUp(string PowerUpType)
{
switch (PowerUpType)
{
case "Shield":
_isShieldActive = true;
//activate shield game object
_shield.SetActive(true);
_shieldHealth = 3;
break;
}
}

Change Shield Color Based on Durability

The bold code parts add the VFX for the shieldhealth. Our shield is using the SpriteRenderer so we use that to change the color.

On Player Hit

We also included our shieldhealth is 0 as a case in our switch statement.

if (_isShieldActive == true)
{
_shieldHealth--;
//UpdateShieldVisual
switch (_shieldHealth)
{
case 3:
_shieldSprite.color = Color.cyan;
break;
case 2:
_shieldSprite.color = Color.green;
break;
case 1:
_shieldSprite.color = Color.red;

break;
case 0:
//deactivate shield gameobject
_shield.SetActive(false);
_isShieldActive = false;
break;
default:
Debug.Log("Player.Shieldvisual switch default value");
break;
}
}
}

On Shield Activation

public void PowerUpPickUp(string PowerUpType)
{
switch (PowerUpType)
{
case "Shield":
_isShieldActive = true;
//activate shield game object
_shield.SetActive(true);
_shieldHealth = 3;
_shieldSprite.color = Color.cyan;
break;
}
}

Add Shield UI

We use the same way as in a previous article.

--

--

Tristan Engel
Tristan Engel

Written by Tristan Engel

Aspiring developer that’s self-learning Unity & C# to transition to a career with Unity. I got a passion for creating interactive experiences.

No responses yet