I have an issue where my attacks (missiles, lazers) etc will trigger on multiple enemies when those enemies are in the exact same position and have the same colliders.
public virtual void OnCollisionEnter2D(Collision2D col){
if (col.gameObject.tag == "Enemy"){
if(collidesEnemy == true){
col.gameObject.GetComponent<Enemy>().takeDamage(baseDamage);
print(gameObject.GetInstanceID());
print(col.gameObject.GetInstanceID());
Destroy(gameObject);
}
}
}
My enemies move towards the player, and when they get stuck in the same position and stack up on each other, since they are prefabs instances they have the same collider dimensions which when in the same position get triggered at the same time.
For example, three zombies are stuck in the same position and so their colliders match up. I shoot a missile at them, the missile deals damage to all three zombies. The missile follows the above code. I have tested this in the print statements from the above code and have confirmed this is the case.
Should your enemies not bump into each other and not overlap? What you could do is set a bool when it first collides so it doesnât run the code on the next call of the collision method.
private bool _collided;
public virtual void OnCollisionEnter2D(Collision2D col)
{
if (!collidesEnemy || _collided)
return;
var enemy = col.gameObject.GetComponent<Enemy>();
if (enemy == null)
return;
_collided = true;
enemy.takeDamage(baseDamage);
Destroy(gameObject);
}
@WarmedxMints_1 already provided a workable solution for this issue; there are others like saving the âtimestampâ or âlastEnemyColliderâ etc that also have the same effect: only hit one enemy collider.
That being said, I think that this is a workaround for a different problem: Zombies shouldnât be able to stack, should they? So if you resolved that issue, your hit detection code would not need to deal with multiple hits (although it is good practice to still implement single-hit just to be sure). Why do you allow the Zombies to overlap? Is that a conscious design decision?
Destroy() is only executed at the end of the Frame. If multiple colliders overlap at the collision point, OnCollision will be called for all overlapping colliders in the same frame, even if one invocation called Destroy().