- Home /
How to make a healthbar made out of discrete elements?
Think hearts in Zelda or health indicator in Enter the Gungeon.
Well, those are not really bars but indicators consisting of seperate icons, as you noted.
You could implement it in various ways. One would be to have a collection of UI Images and every $$anonymous$$m the player increased the max health of his character, add one element to it. The position of the UI element is easily calculated by taking the index value of the new element multiplied by the icon width plus some padding. When the player loses hit points, access the end of the collection and disable those image components.
I apreciate your input, but... Shouldn't that be an answer? :) Thanks.
@Cherno is right, and sometimes we are not sure if the answer is 100% correct, or the question is vague.
Answer by danmartelly_caliper · May 10, 2017 at 01:40 PM
This is how I would set it up
Scene Setup
In your UI Canvas element, make an empty GameObject called "Health bar".
Inside "Health bar" make each of the discrete elements, e.g. "heart1", "heart2", ...
Add a new script component called "HealthTracker" to your "Health bar" game object.
Code
For your "HealthTracker" script have something like this:
using UnityEngine;
using UnityEngine.UI;
public class HealthTracker : MonoBehaviour {
public Image[] hearts;
protected int curHealth;
// max health deteremined by number of heart images
void Start () {
curHealth = hearts.Length;
SetHealth (2);
}
void SetHealth(int newHealth) {
if (newHealth > hearts.Length)
newHealth = hearts.Length; //can't exceed maximum num of hearts
for (int i = 0; i < hearts.Length; i++) {
if (i < newHealth)
hearts [i].color = Color.red;
else
hearts [i].color = Color.white;
}
}
}
Put it together
Finally, in the inspector, assign each discrete element to the "hearts" array for the "Health bar" game object. When you use the SetHealth
function, it will iterate through the hearts array and change that number of hearts to red and the rest to white.
Your answer
![](https://koobas.hobune.stream/wayback/20220612115915im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to make an healthbar 1 Answer
Draw orthographic visuals (e.g. health bar) in perspective scene? 4 Answers
Show changes in healthbar 1 Answer
HealthBar with ColorChange 1 Answer
health bar that scale to the zoom 1 Answer