BrettM
5/20/2019 - 4:56 PM

Managing Enemy Damage

// Ensure the projectile has a collider & is set to *is Trigger*
// Ensure that the enemy has a collider and rigidbody

// On the projectile script
public class Projectile : MonoBehaviour
{
      [SerializeField] int shotDamage = 1;
  
      private void OnTriggerEnter2D(Collider2D other)
    {
            var health = other.GetComponent<AttackerHealth>();
            health.DealDamage(shotDamage);
            Destroy(gameObject);
    }
}

// On the health script
public class AttackerHealth : MonoBehaviour
{
    [SerializeField] int attackerHealth = 3;
       
    public void DealDamage(int damage)
    {       
        attackerHealth -= damage;
        if (attackerHealth <= 0)
        {
            Die();
        }
    }

    private void Die()
    {
        Destroy(gameObject);
    }
}