Enemy Health Bar not destroying on death

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?

1
2
3

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;
}

}

1 Like

Can you tell me where line 20 is? Yeah the UI is null but, that’s cuz it’s not getting info needed as opposed to it not being wired correctly. COOOOOOOULD be when the Unit script is being executed.

Line 20 is this:

So i fixed it finally, looks like it had something to do with the EnemyPrefab being a Prefab Variant of the main Unit.

I just deleted it and made a new enemy unit not as a variant. Still not sure why it wouldnt work in the first place

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms