Can't destroy Game Object in Array

Hello everyone! Sorry for my bad English :slight_smile:

I have a map made of tiles. Using my script I generate some transparent tiles, which are located on the same coordinates as usual tiles. I need to destroy transparent tiles, which have no usual tiles under them. But they aren’t destroyed. My code:

#pragma strict
var tiles : GameObject[,] = new GameObject [32,32];
var GridPrefab : GameObject;
var Contact = Array ();
var x : int;
var y : int;
function Start () {
	for (var i = 0; i < y; i++)
		for (var j = 0; j < x; j++) 
            tiles[j,i] = Instantiate (GridPrefab, Vector3 (j*10, 0, i*10), Quaternion.identity);
}
function Update () {
	for (var i = 0; i < y; i++)
		for (var j = 0; j < x; j++) 
	        Contact = Physics.OverlapSphere (Vector3 (j*10, 0, i*10), 0.1);
	        if (Contact.length != 1)
			Destroy (tiles[j,i]);
}

Replace Destroy (tiles[j,i]); with:

if(tiles[j,i])
    Destroy (tiles[j,i]);

Also replace Contact.length != 1 with Contact.length < 1. Your code should look like this:

if (Contact.length < 1)
    if(tiles[j,i])
        Destroy (tiles[j,i]);

That works good! A cup of coffee makes my brain think. I hope it can help someone in future.

#pragma strict
var tiles : GameObject[,] = new GameObject[32,32]; //Array for transparent grid
var GridPrefab : GameObject; //Prefab of transparent gri
var x : int; //Number of needed tiles
var y : int;
//Making a grid made of transparent prefabs
function Start () {  
	for(var i = 0; i < y; i++)
		for(var j = 0; j < x; j++)
			if(Physics.Raycast (Vector3(j*10, 1, i*10), -Vector3.up, 10)) //Cast a ray, which checks existence of a map tile. If there is no such tile transparent tile won't be generated
            	tiles[j,i] = Instantiate(GridPrefab, Vector3(j*10, 0, i*10), Quaternion.identity);
}