Why could I delete my clones onlY in the same order of instantiation?

Hi! I am kind of new to Unity.

So, I’ve been trying to destroy set of clones on mouse click instantiated during my game play.
My code for instantiation goes like this.

public class inst : MonoBehaviour {
public GameObject ch;

public Transform[] spawnpoint=new Transform[3];	// Use this for initialization
void Start () {
	spwn();
}

void spwn(){
	for (int i=0; i<4; i++) {
		Vector3 spawnVector = new Vector3 (spawnpoint<em>.position.x, spawnpoint_.position.y, spawnpoint*.position.z);*_</em>

_ Instantiate (ch , spawnVector, spawnpoint*.rotation);
}
}
// Update is called once per frame*

* void Update () {*_

* }*
}
And, I have a separate code for destroying the clones on Mouse click which is added to the respective prefab.
But when I am trying to destroy them, they are getting destroyed in the same order in which they
are created.
For eg., if I am clicking on my clone in spawnpoint[2] transform, spawnpoint[0] clone is getting destroyed. And on a second click of the same spawnpoint[1[]'s transform is being destroyed.
Please help me in making my code work properly. Thanks in advance :slight_smile:
p.s.: I might have misunderstood and would have something wrong. I am just a beginner. In that case please correct me.

Encapsulating properly shouldn’t have actually fixed the problem (although it was definitely needed for readability). When you instantiate a GameObject from a prefab they all have the same name, which is their prefab name + “(Clone)”. This is to help identify the ones you’ve spawned in the inspector and so on. When you use GameObject.Find it makes a list of all the gameObjects with that name and then picks the first on the list, which I believe is whichever one is first in the inspector. Since Destroy can only destroy 1 object at a time, it will always destroy the first object it finds with that name. The code you posted originally would have worked just fine, but with a small change.

public class onmouse : MonoBehaviour 
{
    void Update () 
    {
        if(Input.GetMouseButtonDown(0))  
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if(Physics.Raycast(ray, out hit, 10f))
            {
                Debug.DrawRay (ray.origin, hit.point);
                Destroy(hit.transform.gameObject);
            }
        }
    }
}

hit.collider.gameObject should also have worked. The only problem with what you wrote was that you weren’t specific enough with which GameObject you wanted to destroy.

First, try extending your if statement brackets to encapsulate the Destroy routine.

if(mousebutton)
{
    ray and hit setup
    if(raycast)
    {
        Debug
        Destroy
    }
}