How to make a health bar in Unity

In this tutorial, we will learn how to make a health bar for your player. You will design a simple health bar using paint, import it into Unity and use it in your game. Let’s get started.

Designing the health bar.

The design might vary based on your style. I will go ahead with a basic style. You can also download free health bars from Unity asset store.

  1. Let’s make a rectangle with curved edges in Paint.
  2. Save it as a PNG file.
  3. Open the file in GIMP or Photoshop.
  4. Crop the image so that there is no background.
  5. Here is my final image.
health bar sprite

Using the health bar in Unity

  1. Drag and drop the image into your Unity Assets folder.
  2. Select the image and set the type to Sprite (2D and UI).
  3. Adjust pixel per unit so that the image native size matches your requirement.
  4. Add a Canvas and an Event system to your scene.
  5. Create an empty gameobject called Health_bar as a child of canvas.
  6. Adjust the rect transform to make it look like a health bar.
  7. Set the position to your requirement.
  8. Add two UI images as child objects to the Health_bar.
  9. Name one as border and one as fill.
  10. Set the source image as the health bar image you have created.
  11. Set the Alpha value of the border image to less than 50. This will make it look transparent.
  12. Select border UI, press down the alt key, click the anchor preset and select the one in bottom right corner.
  13. Repeat the same for fill image.
anchor settings

Making the health bar into a slider

  1. Select your health bar and go to the inspector window.
  2. Click on add component and select slider.
  3. uncheck interactable and set transition to none.
  4. Drag and drop your fill object into the fill rect parameter.
  5. Now if you adjust the value, you should see your health bar changing.
slider settings

Writing code to control health

Let’s add a cube and a plane object to the scene and reduce the health by 20% when the cube collides with the plane.

  1. Create a new script and attach it to your player. It’s the cube in this case.
  2. Rename the script to health and open the script.
  3. Copy and paste the code below.
using UnityEngine;
using UnityEngine.UI;

public class health : MonoBehaviour
{
    public Slider healthbar;
    int health_value=100;
    

     
    void OnCollisionEnter(Collision col)
    {
        health_value-=20;
        healthbar.value= health_value;

    }
}

Here is the output

Output gif

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Why Creativity is must for game developers How to become a Unity developer? How to Become a Game Developer? VR Game dev Companies: Top 10 Programming Languages used by Unity