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
Thanks in advance
~ Zero