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?
Answer by Cuttlas-U · Apr 06, 2017 at 08:33 PM
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;
Also ensure that you've assigned a Sprite to the Source Image field, or the "Image Type" field won't be displayed. (This was my problem, and why I couldn't access either the Image Type or the Fill Amount fields.)
Answer by mnarimani · Apr 06, 2017 at 08:18 PM
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)).
Answer by LearningWhileScrewing · Nov 16, 2019 at 05:51 PM
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!! } }
Your answer
Follow this Question
Related Questions
Showing player health on UI 1 Answer
Convert global or local position to anchorPosition for a RectTransform? 0 Answers
How to draw texture behind canva ? 0 Answers
Create Button via Script not working 1 Answer
How to forbid float sizes and positions of all UI elements of UGUI while editing? 1 Answer