GUI health status

I have a canvas with a panel, in the panel i want to display an image for each healthpoint the player has, max 20.

The code i use for this is:

float _slots = 0f;
		
		for (int i = 0; i < 2; i++) {
			for (int k = 0; k < 10; k++) {
				if (_slots <= PlayerHealthPoints) { 
					GameObject Heart = (GameObject)Instantiate (HeartImage);
					HeartSlots.Add (Heart);
					Heart.transform.parent = HeartPanel.transform;
					Heart.name = "Heart" + i + "," + k;
					Heart.GetComponent<RectTransform> ().position = new Vector3 (x, y, 0);
					_slots ++;
				}
				x += 50;
				if (k == 9) {
					x = 35;
					y = y - 50;
				}
			}
		}

I can instantiate and show 20 images fine, the problem is showing less if the player has less health, i tried the if statement but its not working.

So I highly suggest making a gameobject with two child images, the first is your overlay the second is your underlay (a grey heart for example).

Then this code should be suitable, attach it your heartPanel:

public class TEST
{
    float playerHealth;

    float slots = 0f;

    float x = 0;
    float y = 0;
    float amountInX;
    float amountInY;

    float heartSlots;
    float health;

    List<GameObject> HeartSlots = new List<GameObject>();

    GameObject heartObject;

    float CalculateHealth()
    {
        return heartSlots = health / 20;
    }

    void Start()
    {
        for (int i = 0; i < amountInY; i++)
        {
            for (int k = 0; k < amountInX; k++)
            {
                GameObject Heart = (GameObject)Instantiate(heartObject);

                HeartSlots.Add(Heart);
                Heart.transform.SetParent(gameObject.transform, false);
                Heart.name = "Heart" + i + "," + k;
                Heart.GetComponent<RectTransform>().position = new Vector3(x, y, 0);
                slots++;

                x += 50;
                if (k == 9)
                {
                    x = 35;
                    y = y - 50;
                }
            }
        }
    }

    void UpdateHearts()
    {
        foreach(GameObject heart in HeartSlots)
        {
            heart.gameObject.transform.GetChild(0).GetComponent<Image>().enabled = false;
        }

        for (int i = 0; i < heartSlots; i++)
        {
            HeartSlots*.gameObject.transform.GetChild(0).GetComponent<Image>().enabled = true;*

}
}

void Update()
{
UpdateHearts();
}
}
Haven’t fully read it through but you get the idea. You’d have to implement bits of it yourself like update the playerHealth etc.