Help with Collision Detection / FindGameObject

Hello,

Hoping someone can help me out here.

I have a spawner that will spawn an enemy prefab, which creates clones of that object, so I have tagged these with “Enemy”. Next I have an arrow that, when it hits one of these enemies it will destroy that gameobj.
My problem is that if I have 3 enemies on the screen, and an arrow hits enemy2 or 3, the first enemy that was spawned is removed, and not the one that was hit with the arrow. (code below). I assume that the way I’m doing it, I’m storing the enemy game objs in a first in first out, however how do I find specifically the one that is hit with the arrow. I cannot simply do GameObject.Find(“Enemy (Clone)”).GetComponent()

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        Destroy(gameObject,5f);
        enemy = GameObject.FindGameObjectWithTag("Enemy");
    }
    void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag != "Arrow")
        {
            //if the Arrow hits another arrow, do not delete
            if (collision.gameObject.tag != "Arrow")
            {
                Destroy(gameObject);
                if(collision.gameObject.tag == "Enemy")
                {
                    //Debug.Log("hit enemy" + enemy);
                    Destroy(enemy);
                }
            }
        }
    }

Thanks in advance.

You don’t use GameObject.Find() in a collision context. The reason is that you have it in the collision argument.

Also, line 3 and line 6 above check the same thing… just delete one of them.

Generally, assuming this script is on the projectile, you check the tag of what you hit and if it can be killed, you Destroy() the collision.gameObject.

See enclosed “HitThings” package for fully functional projectile and possible targets example. For simplicity since tags cannot be easily exported by package, the code example below uses the name of the object it hits to decide if it is “hittable.” You’re welcome to use tags instead.

Script:

using UnityEngine;

// @kurtdekker
// just checks the name of what we hit, not the tag; you can check the tag; whatever.
// put this on the projectile.

public class HitThings : MonoBehaviour
{
    const string s_Hittable = "Hittable";

    void OnCollisionEnter( Collision collision)
    {
        if (collision.gameObject.name == s_Hittable)
        {
            Debug.Log( "Hit a hittable!");

            Destroy(gameObject);    // destroy us (projectile)

            Destroy(collision.gameObject);    // destroy what we hit
        }
        else
        {
            Debug.Log( "Hit something not hittable.");
        }
    }
}

6661057–761818–HitThings.unitypackage (30.5 KB)