Destroy(this.Object) destroys ALL instances

Hello guys. I am trying to make a two dimmensional field for growing crops, that will be saved in a 2D array [so it doesn’t get destroyed when the player changes a map and comes back, and can be saved to a file]

I have made it instantiate a “Field” prefab in a nested FOR loop [later on it will read values from the mapData, and place the plants accordingly] - the problem is, when I try to detect a mouse click, as a test, for one of the fields, and make it get destroyed, ALL of the instances [fields] get destroyed by that. I have dug throught google for similar problems, but none seemed to help me in fixing that problem.

The method which instantiates the map [no data reading yet, just a simple instantiate]:

public void generateMap()
    {
        for (int x = 0; x < 10; x++)
        {
            for (int y = 0; y < 10; y++)
            {
                GameObject newField = (GameObject)Instantiate(emptyField, new Vector3(11.5f + x, 1.5f + y, 0), Quaternion.identity);

                //FieldData fData = newField.GetComponent<FieldData>();
                //fData.fieldPos = new Vector2(x, y);
            }
        }
    }

The code for destroying a field on mouse click [is inside the script attached to each field]:

void Update () {

        if (Input.GetMouseButton(0))
        {
            setFieldID(0);
        }

}

You’re not checking which field is being clicked. Input.GetMouseButton will be true on all scripts when the mouse is clicked, thus it sets each fields id to 0.

You will need to check which field contains the mouse cursor and set that field’s id to 0. Assuming you have a collider on the GOs, then something like

if (Input.GetMouseButton(0) && collider.bounds.Contains(Input.mousePosition))

should work.

I would recommend, however, that you use the OnMouseDown function.

so instead of having that in your Update, just have

void OnMouseDown(){
    setFieldID(0);
}

I assume ‘setFieldID(0)’ method destroys the object? Right now you are using Input.GetMouseButton(0) which will return true for all of your objects. One approach is to use OnMouseButtonDown() instead:

 void OnMouseButtonDown()
 {
        setFieldID(0);
 }

Another approach is to use Raycasting. That approach is a bit more complicated, but is more mobile friendly.