And this is the health manager script on the enemy
public float enemyCurrentHealth;
public float enemyMaxHealth;
//Functions
public void HurtEnemy(float damageToGive){
enemyCurrentHealth -= damageToGive;
Debug.Log("Damage Done");
}
private void LateUpdate()
{
if(enemyCurrentHealth == 0f){
Destroy(gameObject);
}
}
Debug.Log shows me that each collision is registered and HurtEnemy function is ran on each collision but it doesn’t always subtract health and I can’t understand why. Any help on the subject would be appreciated.
It might ,it might not be cause.
collision is happening in physics fixedupdate so it is out of sync with update. plus getting component in every update is of course very expensive.
As you can see, OnTrigger events are called well before Update, so if you’re making contact as soon as the object is instantiated you’ll be calling your OnTrigger event before you’ve had a chance to define a value for damageToGive. I would recommend moving that line to a Start function or making it into a property instead!
public GameObject Player;
[SerializeField] private float damageToGive;
private float damageToGiveProperty { get { return Player.GetComponent<PlayerDamageManager>().playerDamage; } }
//You can do it this way
private void Start()
{
damageToGive = Player.GetComponent<PlayerDamageManager>().playerDamage;
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Enemy")
{
other.gameObject.GetComponent<EnemyHealthManager>().HurtEnemy(damageToGive);
//OR this way with a property
other.gameObject.GetComponent<EnemyHealthManager>().HurtEnemy(damageToGiveProperty);
Debug.Log("It collides");
}
}