How to make a health script for a custom health bar (In A Canvas)?

Hi Unity Community!

I made a custom ‘bar’ for my Health, Stamina, Thirst and Hunger. And i placed them in my canvas, but how do i make an script to make the health (and stamina, thirst, hunger) go down (or up) in a canvas?
And how do i make it work?

Hi
in the image component u should change the “Image Type” from “simple” to “Filled”

then then there will be an new variable named " Fill Amount"

u can change this value from your script like this :

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

 
    public void Start()
    {
        GetComponent<Image>().fillAmount = 0.5f;
    }

fillAmount valuse is always between 0 and 1 so if u want to change that if your health is for example 50 u can do it like this :

   GetComponent<Image>().fillAmount = health / 100 ;

this way the final amount is 0.5f that will be half of that bar;

Assume you have a border for your ‘bar’ and an image in it (that shows current health or anything that you want).

Add Mask to your border, when you want to change the current health, you just need to move the image inside the border (move it up or down using transform.Translate(Vector3 movement)).

Documentation for Mask

private int health = 1;
public Image heart;

void Start() {
heart = GetComponent();
}

void Update() {
if(health == 1) {
heart.enabled = true;
}
if(health == 0) {
heart.enabled = false;
// here add death animation or something what happens when you die!!
}
}