When i run my game all the code works except when i kill my enemy unit i get a NullRefException for the UnitWorldUI script. I have enemy unit set as the Unit and Health System in the inspector but not sure what the issue is?
public class UnitWorldUI : MonoBehaviour
{
[SerializeField] private TextMeshProUGUI actionPointsText;
[SerializeField] private Unit unit;
[SerializeField] private Image healthBarImage;
[SerializeField] private HealthSystem healthSystem;
private void Start()
{
Unit.OnAnyActionPointsChanged += Unit_OnAnyActionPointsChanged;
healthSystem.OnDamaged += HealthSystem_OnDamaged;
UpdateActionPointsText();
UpdateHealthBar();
}
private void UpdateHealthBar()
{
healthBarImage.fillAmount = healthSystem.GetHealthNormalized();
}
private void HealthSystem_OnDamaged(object sender, EventArgs e)
{
UpdateHealthBar();
}
private void UpdateActionPointsText()
{
actionPointsText.text = unit.GetActionPoints().ToString();
}
private void Unit_OnAnyActionPointsChanged(object sender, System.EventArgs e)
{
UpdateActionPointsText();
}
}
public class HealthSystem : MonoBehaviour
{
public event EventHandler OnDead;
public event EventHandler OnDamaged;
[SerializeField] private int health = 100;
private int healthMax;
private void Awake()
{
healthMax = health;
}
public void Damage(int damageAmount)
{
health -= damageAmount;
if (health < 0)
{
health = 0;
}
OnDamaged?.Invoke(this, EventArgs.Empty);
if(health == 0)
{
Die();
}
}
private void Die()
{
//invoke the ondead function in Unit script which destory's obj
OnDead?.Invoke(this, EventArgs.Empty);
}
public float GetHealthNormalized()
{
return (float)health / healthMax;
}
}