Unity Image fill amount for a Health Bar

Today let’s talk about such property as fillAmount for Image objects in Unity3D.

There’s a pretty common case of UI in video games – a health bar. It often looks like a stripe filled with some color or gradient.

healthbar unity fillamount healthbar Image fill amount

The algorithm of a health bar is easy. All you need to have is:

  • container – the object that should be filled
  • the bar image – the object that change its size according to a health amount

Using the fillAmount to implement a health-bar image in Unity

Unity by itself contains a feature to control the level of a health bar. Select the health image in Unity editor and set a property Image Type to Filled.

Then choose the Fill Method. In our case it should be Horizontal.

unity-fill-amount

And now you can interact with the health bar using an API. Don’t forget to import UnityEngine.UI package in the code.

Image playerHealth;
	
void Start () {
	playerHealth = GameObject.Find("PlayerHealth").GetComponent<Image> ();
}

void Update () {
	playerHealth.fillAmount = player.health / 100f;
}

The code above will keep the health bar in the actual condition. When you decrease player’s health it would take effect to a health image.

Leave a Reply

Be the First to Comment!