I can’t get my health sprite to change when my player health is at a certain level.
I am really not sure how to fix it or explain what is going on. When I run my game, it shows on the console that my health is full. However when I take one damage it doesn’t show that my health has lowered.
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
public class HealthSystem
{
public int health;
public int maxHealth;
public Image hpImage;
private Sprite hp;
public HealthSystem(int maxHealth)
{
this.maxHealth = maxHealth;
health = maxHealth;
}
public int GetHealth()
{
return health;
}
public void Damage(int damageAmount)
{
health -= damageAmount;
if (health < 0)
{
health = 0;
}
}
public void Heal(int healAmount)
{
health += healAmount;
if (health > maxHealth)
{
health = maxHealth;
}
}
}
______________________________________________________________________________________________________
public class Player_UI : MonoBehaviour
{
private bool plusOneDmg;
private bool healOneHeart;
private bool padHit = false;
public Image healthImg;
HealthSystem healthSystem = new HealthSystem(4);
private void Start()
{
Debug.Log("Health:" + healthSystem.GetHealth());
}
private void Update()
{
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Lava" && padHit == false)
{
healthSystem.Damage(1);
Debug.Log("Health:" + healthSystem.GetHealth());
padHit = true;
}
else if (collision.gameObject.tag == "HealCube" && padHit == false)
{
healthSystem.Heal(1);
Debug.Log("Health:" + healthSystem.GetHealth());
padHit = true;
}
}
private void OnCollisionExit2D(Collision2D collision)
{
if (collision.gameObject.tag == "Lava" && padHit == true)
{
padHit = false;
}
else if (collision.gameObject.tag == "HealCube" && padHit == true)
{
padHit = false;
}
}
}
[RequireComponent(typeof(Image))]
public class HealthBar : MonoBehaviour
{
public Sprite Hp4, Hp3, Hp2, Hp1, Hp0;
public Image image;
HealthSystem healthSystem = new HealthSystem(4);
private void Start()
{
hpBar();
image = gameObject.GetComponent<Image>();
}
private void Update()
{
}
private void hpBar()
{
if (healthSystem.health == healthSystem.maxHealth)
{
Debug.Log("FullHp");
image.sprite = Hp4;
}
if (healthSystem.health == 3)
{
Debug.Log("LessHp");
image.sprite = Hp3;
}
if (healthSystem.health == 2)
{
Debug.Log("LesserHp");
image.sprite = Hp2;
}
if (healthSystem.health == 1)
{
Debug.Log("EvenLesserHp");
image.sprite = Hp1;
}
if (healthSystem.health == 0)
{
Debug.Log("NoHp");
image.sprite = Hp0;
}
}
}