Second Enemy won't get killed unless first one is destroyed.

Hello to anyone who knows the answer

The following is my script.

void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.tag == "Enemy")
    {
        FindObjectOfType<Goomba>().Flipped(); // Kill the Enemy
        Destroy(gameObject);
    }
}

I shoot the first enemy, it should take some time before it is destroyed. Meanwhile, when I shoot the second enemy, the one being shot is still the first enemy. and Second enemy won’t die, unless first one is destroyed in unity game. Does any one know why?

Thank you.

You need use the reference of the collisioned enemy, not use “FindObjectOfType” , because will grab the first game object that match that description.

    private void OnCollisionEnter2D(Collision2D collision)
    {
       if (collision.gameObject.tag == "Enemy")
       {
            var enemy = collision.gameObject.GetComponent<Goomba>();
            enemy.Flipped();
            Destroy(collision.gameObject);
       }
    }

I think you need to use this instead:

collision.gameObject.GetComponent<Goomba>().Flipped(); 

as it will grab the script on the gameObject that collided.

FindObjectOfType just returns the first object of this type given.
which happens to be your first enemy.