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.
- Let’s make a rectangle with curved edges in Paint.
- Save it as a PNG file.
- Open the file in GIMP or Photoshop.
- Crop the image so that there is no background.
- Here is my final image.
Using the health bar in Unity
- Drag and drop the image into your Unity Assets folder.
- Select the image and set the type to Sprite (2D and UI).
- Adjust pixel per unit so that the image native size matches your requirement.
- Add a Canvas and an Event system to your scene.
- Create an empty gameobject called Health_bar as a child of canvas.
- Adjust the rect transform to make it look like a health bar.
- Set the position to your requirement.
- Add two UI images as child objects to the Health_bar.
- Name one as border and one as fill.
- Set the source image as the health bar image you have created.
- Set the Alpha value of the border image to less than 50. This will make it look transparent.
- Select border UI, press down the alt key, click the anchor preset and select the one in bottom right corner.
- Repeat the same for fill image.
Making the health bar into a slider
- Select your health bar and go to the inspector window.
- Click on add component and select slider.
- uncheck interactable and set transition to none.
- Drag and drop your fill object into the fill rect parameter.
- Now if you adjust the value, you should see your health bar changing.
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.
- Create a new script and attach it to your player. It’s the cube in this case.
- Rename the script to health and open the script.
- 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