Unity How to create a health bar

Design a health bar.png and in Import settings place the Pivot point on 'Left'. This way when it scales down it does so to the left. Drag the health bar texture in your scene. Attach a health bar script to it.

HealthBar.cs
using UnityEngine;
using System.Collections;
 
public class HealthBar : MonoBehaviour {
	void Start () {
	}
 
	void Update () {
	}
 
        // normal health is 100
	public void setHealth(float newHealth) {
		renderer.material.color = Color.Lerp(Color.green, Color.red, 1 - health * 0.01f);
		transform.localScale = new Vector3(transform.localScale.x * health * 0.01f, 1, 1);
	}
}

Now when the health bar needs to decrease call the setHealth() method from another script. In below example the health bar object/texture was named 'health_bar'. First we find that GameObject and then find the attached script.

OtherScript.cs
// getting health_bar child and script
Transform child = gameObject.transform.Find("health_bar");
HealthBar script = child.GetComponent<HealthBar>();
script.setHealth(newHealth);
Navigation
Print/export
Toolbox