I am working on my first Tower Defense game and I have a problem where multiple enemies get hit by a projectile instead of one.
Enemy with its collider:
The problem is that when the enemies get close to each other, their colliders overlap and one arrow deals damage to multiple units.
Arrow and Enemy both have trigger colliders 2D.
Code for Arrow.cs component:
private void OnTriggerEnter2D(Collider2D collision) {
Enemy enemy = collision.GetComponent<Enemy>();
if (enemy != null) {
IDamagable damagable = enemy.GetComponent<IDamagable>();
if (damagable != null) {
damagable.ReceiveDamage(DamageType.PHYSICAL, attackType, damage);
} else {
Debug.Log("Unit is missing the IDamagable script");
}
Destroy(gameObject);
}
}
Seems like collision detection and OnTriggerEnter2D is called in the same step and this function runs multiple times even if the game object is destroyed.
this==null
. Seems absurd, but that is just checking if the object has been marked as destroyed. The thing is that MonoBehaviours don't immediately stop existing when you callDestroy()
, so it's possible that multiple callbacks that are happening on the same physics step have already been queued up by the time you destroy the object, and they all end up executing anyways. \$\endgroup\$if (enemy != null)
\$\endgroup\$