Resources.Load is setting source of Image to None

Hello,
I am trying to implement a health system in my game. It is 1 image made up of 4 hearts. When the player takes damage the Image is updated to a sprite with the correct amount of hearts. When I run the game and take damage the Image changes to the default white box for a UI image and in the inspector the source changes to “none”. I have my sprites inside of the “Resources” folder. I ran Debug.Log so I know the string is correct.

Here is the code:

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

public class PlayerHealth : MonoBehaviour {

    public int CurrentHealth = 4;
    public Image HealthBar;


    public void TakeDamage(int amount)
    {
        CurrentHealth -= amount;
        this.ChangeImage();
    }
    private void ChangeImage()
    {
        string ImageName;
        switch (this.CurrentHealth)
        {
            case 4:
                ImageName = "hearts4";
                break; 
            case 3:
                ImageName = "hearts3";
                break;
            case 2:
                ImageName = "hearts2";
                break;
            case 1:
                ImageName = "hearts1";
                break;
            default:
                ImageName = "hearts0";
                break;
        }
        Debug.Log(ImageName);
        this.HealthBar.sprite = Resources.Load<Sprite>(ImageName);
    }
}

Images I am trying to load
99244-hearts.png

Thanks in advance
~ Zero

It’s just a guess but I could imagine that Resources.Load can only load “hearts” as the actual resource in this context. hearts0 to hearts4 are just children of that resource.

In any case, I’d not use Resources.Load for this anyway. Resources.Load is more for cases in which you want to have control over when a resource is loaded and unloaded. Here, the hearts texture needs to be loaded constantly in the scene because you are displaying one of the sprites at all times. So instead, just do this:

[SerializeField]
private Sprite[] heartSprites;

drag and drop your heart sprites in this field in the inspector, starting with hearts0.

Then, change ChangeImage to this:

private void ChangeImage()
{
  HealthBar.sprite = heartSprites[CurrentHealth];
}

That would be all. As you can see, this is also way more compact. The only thing you need to be aware of is that there will be an exception thrown if you ever happen to have a health amount outsie 0 to 4.