Health Bar UI

World-space or screen-space health bar with smooth fill, color gradient, and damage flash. Attach to enemies or use as HUD.

File
HealthBarUI.cs
Unity
2022.3+
Level
beginner
Size
2.4 KB · 107 lines
Added
2026-03-05
License
MIT
View source

No APIs that Unity 6.0 to 6.6 made obsolete or removed. How this is checked

A Pro version adds more: Health Bar UI Pro.

What it adds to your GameObject

A MonoBehaviour component: attach it to a GameObject. This is the Inspector you get, read from the source: 8 serialized fields with their defaults.

Inspector
Script HealthBarUI
References
Fill Image None (Image)
Background Image None (Image)
Fill Settings
Smooth Speed 5
Color Gradient None (Gradient)
Damage Flash
Enable Damage Flash
Flash Color
Flash Duration 0.15
Billboard (World Space Only)
Billboard To Camera

When to use it

Use in any game that displays health visually — RPGs with enemy health bars above their heads, FPS games with HUD health displays, boss fight health bars, or even vehicle/structure health indicators. Works both as a world-space bar floating above enemies and as a screen-space overlay HUD element.

Setup

  1. Create a Canvas (World Space for enemies, Overlay for HUD)
  2. Add a background Image and a child fill Image (set fill type to Horizontal)
  3. Attach HealthBarUI, assign both images
  4. Connect to HealthSystem: OnHealthChanged.AddListener(healthBar.SetHealth)
  5. Enable Billboard for world-space bars to face camera
  6. Customize the color gradient (red→yellow→green by default)

Features

  • Smooth fill animation with Lerp for satisfying health changes
  • Color gradient that shifts from green to yellow to red automatically
  • Damage flash effect on the background image when health decreases
  • Billboard mode for world-space bars to always face the camera
  • SetHealthImmediate method to skip animation for instant updates
  • Default gradient auto-generated if none is configured in Inspector

Inspector fields

Every field Health Bar UI exposes in the Inspector, with the default it starts at.

FieldTypeDefaultGroup
Fill ImagefillImageImageNoneReferences
Background ImagebackgroundImageImageNoneReferences
Smooth SpeedsmoothSpeedfloat5Fill Settings
Color GradientcolorGradientGradientNoneFill Settings
Enable Damage FlashenableDamageFlashbooltrueDamage Flash
Flash ColorflashColorColor#FFFFFFDamage Flash
Flash DurationflashDurationfloat0.15Damage Flash
Billboard To CamerabillboardToCamerabooltrueBillboard (World Space Only)

Public API

What other scripts can call on HealthBarUI.

MemberReturnsDescription
SetHealth(float current, float max)voidUpdate the health bar. Call this from HealthSystem.OnHealthChanged.
SetHealthImmediate(float current, float max)voidSet fill instantly without smoothing.

Requirements

  • Uses uGUI (UnityEngine.UI): needs a Canvas in the scene.

Common mistakes

The fill Image must have its Image Type set to Filled with Fill Method set to Horizontal in the Inspector — otherwise fillAmount has no visible effect. If the color gradient isn't assigned, the script creates a default one, but only if the existing gradient has 1 or fewer color keys. For world-space bars, make sure the Canvas Render Mode is set to World Space, not Screen Space.

Source code

HealthBarUI.cs, 107 lines, MIT licensed. Paste it into a new C# file of the same name.

HealthBarUI.cs
C#
using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// Health bar UI with smooth fill animation and color gradient.
/// Works as world-space (enemy) or overlay (HUD) health bar.
/// </summary>
public class HealthBarUI : MonoBehaviour
{
    [Header("References")]
    [SerializeField] private Image fillImage;
    [SerializeField] private Image backgroundImage;

    [Header("Fill Settings")]
    [SerializeField] private float smoothSpeed = 5f;
    [SerializeField] private Gradient colorGradient;

    [Header("Damage Flash")]
    [SerializeField] private bool enableDamageFlash = true;
    [SerializeField] private Color flashColor = new Color(1f, 1f, 1f, 0.6f);
    [SerializeField] private float flashDuration = 0.15f;

    [Header("Billboard (World Space Only)")]
    [SerializeField] private bool billboardToCamera = true;

    private float targetFill = 1f;
    private float currentFill = 1f;
    private float flashTimer;
    private Color originalBgColor;

    private void Awake()
    {
        if (backgroundImage != null)
            originalBgColor = backgroundImage.color;

        // Set default gradient if none assigned
        if (colorGradient.colorKeys.Length <= 1)
        {
            GradientColorKey[] keys = new GradientColorKey[3];
            keys[0] = new GradientColorKey(new Color(0.9f, 0.2f, 0.2f), 0f);    // Red at low
            keys[1] = new GradientColorKey(new Color(0.9f, 0.7f, 0.1f), 0.5f);   // Yellow at mid
            keys[2] = new GradientColorKey(new Color(0.2f, 0.9f, 0.3f), 1f);     // Green at full

            GradientAlphaKey[] alpha = new GradientAlphaKey[2];
            alpha[0] = new GradientAlphaKey(1f, 0f);
            alpha[1] = new GradientAlphaKey(1f, 1f);

            colorGradient.SetKeys(keys, alpha);
        }
    }

    private void Update()
    {
        // Smooth fill
        currentFill = Mathf.Lerp(currentFill, targetFill, Time.deltaTime * smoothSpeed);
        if (fillImage != null)
        {
            fillImage.fillAmount = currentFill;
            fillImage.color = colorGradient.Evaluate(currentFill);
        }

        // Damage flash
        if (flashTimer > 0f)
        {
            flashTimer -= Time.deltaTime;
            if (flashTimer <= 0f && backgroundImage != null)
                backgroundImage.color = originalBgColor;
        }
    }

    private void LateUpdate()
    {
        // Billboard: face camera
        if (billboardToCamera && Camera.main != null)
            transform.forward = Camera.main.transform.forward;
    }

    /// <summary>
    /// Update the health bar. Call this from HealthSystem.OnHealthChanged.
    /// </summary>
    public void SetHealth(float current, float max)
    {
        float previous = targetFill;
        targetFill = Mathf.Clamp01(current / max);

        // Flash on damage
        if (enableDamageFlash && targetFill < previous && backgroundImage != null)
        {
            backgroundImage.color = flashColor;
            flashTimer = flashDuration;
        }
    }

    /// <summary>
    /// Set fill instantly without smoothing.
    /// </summary>
    public void SetHealthImmediate(float current, float max)
    {
        targetFill = Mathf.Clamp01(current / max);
        currentFill = targetFill;
        if (fillImage != null)
        {
            fillImage.fillAmount = currentFill;
            fillImage.color = colorGradient.Evaluate(currentFill);
        }
    }
}

Next step

Health Bar UI ProAdvanced health bar with delayed damage indicator, shield overlay, boss mode with phase markers, and segmented health display.