I'm somewhat new to Unity and am trying to build a battle system. Right now, I have an attack that checks collisions with enemy objects like this:
private void OnTriggerEnter2D(Collider2D other) {
if (other.gameObject.layer != LayerMask.NameToLayer(_hurtboxLayer))
return;
var enemyHealth = other.GetComponent<Health>();
enemyHealth.TakeDamage(_damagePoints);
}
My game also uses Rigidbody2D objects to let the player and enemies bump into each other. Because I want the "bumping" Collider2D be different from the hitbox Collider2D, I made a child GameObject called Hurtbox for each enemy. The Hurtbox objects have a Health behaviour which handles the HP and death of an enemy:
public class Health : MonoBehaviour {
[SerializeField] private int _initialHealthPoints;
private int _healthPoints;
public void TakeDamage(int damagePoints) {
_healthPoints -= damagePoints;
if (_healthPoints <= 0) {
Die();
}
}
private void Die() {
Destroy(gameObject);
}
private void Start() {
_healthPoints = _initialHealthPoints;
}
}
The Die
method only destroys the hurtbox object and is not allowed to destroy the enemy object, which is its parent.
Is there any way I can put both Collider2Ds and the Health behaviour on the same GameObject and only check a specific Collider in the OnTriggerEnter2D
method?
Die
method before, I would only destroy the Hurtbox object, not the parent object that holds the Rigidbody, SpriteRenderer, etc. But I just checked now, the code works fine, if I attach the Health behaviour to the Hurtbox object and then callDestroy(transform.parent.gameObject)
fromDie
. \$\endgroup\$