❤️

Creating a Simple Health Bar in Unity

May 30, 2025

Unity Tutorial: Creating a Simple Health Bar

Setting Up the Canvas

  • Create a Canvas
    • Set the scale mode to Scale with Screen Size.
    • Set the resolution to 1920x1080.

Creating the Health Bar UI

  • Create a UI Image as a child of the Canvas:

    • Change its sprite to a square.
    • Set the color to black.
    • Resize to fit your game.
    • Rename this image to border.
  • Duplicate the Border Image:

    • Change its color to red.
    • Slightly downsize it.
  • Duplicate the Red Image:

    • Change its color to green.
    • Change image type to Filled.
    • Set fill method to Horizontal.
    • Set fill origin to Left.

Creating the Health Manager in Unity

  • Create an Empty Game Object:

    • Name it Health Manager.
  • Create a C# Script:

    • Name the script Health Manager.
    • Attach the script to the Health Manager Game Object.

Writing the Health Manager Script

  • Include UnityEngine.UI

  • Declare Public Variables:

    • For the health bar image.
    • For a float variable to track health amount.
  • Implement Functions:

    • Take Damage Function:

      • Accepts a float argument called damage.
      • Subtract damage from health value.
      • Set health bar fill amount to health divided by max health.
    • Heal Function:

      • Accepts a healing amount argument.
      • Add the healing amount to health.
      • Clamp health between 0 and max health.
      • Update the health bar fill amount.
  • Update Method:

    • Check if the Enter key is pressed:
      • Call Take Damage function with a specified damage amount.
    • Check if the Space Bar is pressed:
      • Call Heal function with a specified heal amount.
    • Check if player's health is less than or equal to zero:
      • Reload the scene.

Testing in Unity

  • Drag the Green Health Bar Image into the Health Manager script.
  • Press Play:
    • Use the Enter key to damage the player.
    • Use the Space Bar to heal the player.
    • Observe the health bar updating accordingly.

This tutorial shows a simple method to create a health bar in Unity. Feedback and suggestions for future tutorials are welcome in the comments. Thank you for watching!