Think hearts in Zelda or health indicator in Enter the Gungeon.
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 *.color = Color.red;*
-
else*
_ hearts .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.