Problem with bullet colliding with multiple enemies instead of one

I have a bullet script that trigger on collision with an enemy, problem is when two enemies colliders overlaps and trigger with bullet both disapear instead of one only. Is there any way to only trigger one?

private void OnTriggerEnter2D(Collider2D collision)
{
   if (collision.GetComponent<Enemy>())
   {
       collision.GetComponent<Enemy>().DisableUnit();
       gameObject.SetActive(false);
   }
}

Collisions are evaluated by physics, if one frame the bullet is in the air and the next frame the bullet is within two unit colliders OnTriggerEnter will be called for both concerned colliders.

What you could do is have a variable on the bullet object that acts as an active flag. Because even though you’re disabling the gameObject OnTriggerEnter will get called for all objects collided before the end of the frame.

private bool active = true;
private void OnTriggerEnter2D(Collider2D collision)
{
   if (active && collision.GetComponent<Enemy>())
   {
       collision.GetComponent<Enemy>().DisableUnit();
       gameObject.SetActive(false);
       active = false;
   }
}

That way when the second OnTriggerEnter gets called active will be false and the enemy won’t be disabled.

1 Like