when trying to destroy more than one enemy it will destroy a different one to the one I tried to

Hey all,

I’m making a 2D game where if you jump on the Enemies head (which is where a empty object with a box collider 2D that is set to trigger is on it) it will destroy the gameObject, it works really well with one enemy but the second there is two it will delete in Numerical order.

i have two scripts, one for the enemy and detecting whether or not it’s health is low enough to destroy and one for detecting the if the Player has collieded with the enemies head collider.

PlayerMove.cs

` void OnTriggerEnter2D(Collider2D col)
{

    if (col.gameObject.name == "InflictDamage")
    {

        GameObject.FindGameObjectWithTag("Enemy").GetComponent<EnemyScript>().EnemyHealth -= DamageInflict;

    }
    
 }

}`

EnemyScript.cs

`void Update()
{
transform.Translate(Time.deltaTime * -1, 0, 0);

    if (EnemyHealth <= 1)
    {
        GameObject.Find("Player").GetComponent<PlayerMove>().DeathSound.Play();
        Destroy(gameObject);
    }
}`

FindGameObjectWithTag returns the GameObject which is placed upper in the hierarchy.
It’s not a good practice too.
In your case you should use “this.gameObject.getcomponent…” for getting the Object the script is attached to or “col.gameObject.getcomp…” for the object it is collided with.

FindGameObjectWithTag searches the scene for objects with the tag provided and returns the first found game object. This means it will always return the first “Enemy” object in your hierarchy.

Fortunately, you don’t have to use it. In your OnTriggerEnter2D method you already have a reference to the enemy you want. The col.transform holds a reference to the transform of the game object you have collided with. If it is a child of your enemy object, you can get a reference to the enemy object transform by using col.transform.parent, or get a game object reference by using col.transform.parent.gameObject.