Destroy only one object instead of all

Hello guys. I have a small problem.
I have 4 different objects A ( lets say A1,A2,A3,A4) rolling over 4 different objects B(lets say B1,B2,B3,B4). The order doesnt matter. Objects A are spawning randomly. so Any A can go over any B. When i press on any B i want to delete objects A thats only over the object B im clicking it. Instead when i click on any object B its destroying any object A thats on any object B at that moment.

So short question:
How to destroy any A objects colliding only with a certain B that i click on?

Here is my code:

List<GameObject> collisionList = new List<GameObject>();

    void Update()
    {//Detecting the click on gameobject with tag "cube"
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit))
           //Objects B are the only ones tagged "cubes"
                if (hit.transform.gameObject.tag == "cubes")
                {
                    foreach (GameObject z in collisionList)
                    {
                        Destroy(z);
                    }
                }
                 }
    }

    // Add the GameObject collided with, in a list, when entering
    void OnTriggerEnter(Collider col)
    {
        collisionList.Add(col.gameObject);
    }

   
    // Remove the GameObject from the list on exit
    void OnTriggerExit(Collider col)
    { 
        collisionList.Remove(col.gameObject);
   }

Thank you!

I’m guessing the issue is in your Input.GetMouseButtonDown. Since that checks for the mousebutton down, you’re adding the raycast on top of it, which checks if you hit a cubes object and if you did, then it just triggers the update on each cubes to destroy their stuff.

You might have better luck with the ipointerdown/ipointerup/ipointerclick event system. Or, you may be better off having the click code on a manager object so that when you click, you get the gameobject that you hit, get the script that is attached to it, and call a method on that script to destroy all of it’s objects.

Otherwise, in your if (hit.transform.gameObject.tag …etc if statement, I think you can also do hit.gameObject == gameObject to only hit the loop on the current object.

if (hit.transform.gameObject.tag == "cubes")

becomes

if (hit.gameObject.CompareTag("cubes") && hit.gameObject == gameObject)
1 Like

Wow. It actually did the trick. I looped the current gameObject. Thank you so much.