# Destroy GameObject as an Array of Transform instantiated destroying the whole array

I am trying to destroy a GameObject with the Destroy() method, but when I call it the whole array is destroyed, not just that element.

//Instantiating the prefabs
public Transform[] blue;

foreach (Vector3 vec in xyid)
{
//vec.z is used as the object id
Instantiate(blue[vec.z], new Vector3(vec.x, vec.y), Quaternion.identity);
}


This is another script, I put this on every prefab

void Update () {

if (Input.GetMouseButtonDown(0))
{
Destroy(gameObject);
}

}

• You don't need to put tags in the title, those go in the tags area.
– House
Oct 2 '14 at 14:20
• It's not really clear what your problem is. Please try to be more specific. (Which array is being destroyed?). You should also be aware that Input.GetMouseButtonDown just reports true when you click that button, not when you click the object with that action. So every object that has this script will be destroyed whenever you click the left mouse-button (anywhere on the screen). Oct 2 '14 at 14:54
• Yeah bummzack, figured this out with the Byte56 answer :) Thanks both of you, I just posted the answer below. Oct 2 '14 at 16:30

That's because every object has a script attached that's listening for a mouse down event. Each one checks to see if the mouse is down, and if it is, destroys itself.

It's not clear how you want to select which object to destroy, but there are a few options:

• Use colliders on the objects you want to destroy, and inside the OnMouseDown method, put your destroy code. This will only activate if the left mouse button is pressed while the cursor touches the collider.
• Pull the destroy code out of the object itself and put it in the same script where you generated the objects. Then you can destroy one at a time, be it each object in the array one click at a time, or by some other means you decide in that code.
• I prefer the first approach, but I am already using a "Circle Collider 2D" on every prefab (Material is "None") Oct 2 '14 at 14:23
• When using the OnMouseDown method, it does nothing. void OnMouseDown() { Destroy(gameObject); } Oct 2 '14 at 14:30
• Make sure you check the documentation. Otherwise you'll have to post a new question with more details on the problem. You can also go with the second option, which would allow you more control. Cast a ray of your own and check what it collides with when the mouse button is pressed.
– House
Oct 2 '14 at 14:48

OK, found the answer, BTW its a 2D game solution, forgot to tell

if (Input.GetMouseButtonDown(0))
{

RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
if (hit.collider != null)
{
Destroy(hit.collider.gameObject);
}
}