Finding a item in a List using a raycast.

Hello, I’m trying to find a way to get a gameobject using a raycasthit, remove said object from my List, and destroy the gameobject. I can handle the destroy part just fine, but if I don’t remove it from my List, I get null-reference errors. Can someone please tell me how to find the object in my List?

Code for list: (generates a minecraft-like world of blocks and puts each block into the List.)

import System.Collections.Generic;
var prefab : Transform;
var prefab2 : Transform;
var prefab3 : Transform;
static var blocklist : List.<Transform> = new List.<Transform>();

function Awake(){
	for (var z = -10; z < 31; ++z)
	for (var x = -10; x < 31; ++x)
	for (var y = -4; y > -11; --y) {
		if (y == -4){
	    	var cube = Instantiate (prefab2, Vector3( 0, 0, 0), Quaternion.identity);
	    	cube.transform.position = transform.position + Vector3(x, y, z);
	    	}
	    else if (y < -4 && y > -9){
	    	cube = Instantiate (prefab3, Vector3( 0, 0, 0), Quaternion.identity);
	    	cube.transform.position = transform.position + Vector3(x, y, z);
	    	}
	    else{
	    	cube = Instantiate (prefab, Vector3( 0, 0, 0), Quaternion.identity);
	    	cube.transform.position = transform.position + Vector3(x, y, z);
	    	}
	    blocklist.Add(cube);
	}
}

Code for raycast:

function Erase() {
    if (HitBlock()){
        if (hit.transform.gameObject.name != "basecube(Clone)"){
        	//Destroy gameObject;
        }
    }
}

for ( var index : int = 0; index < blocklist.Count; index++ ) {
if ( blocklist[index] == hit.gameObject ) {
blocklist.RemoveAt(index);
break;
}
}

Count may be length. shrug

Just for the record, the List class has already an Remove function which does what you want:

blocklist.Remove(hit.gameobject.transform);

However if you’re going to delete many blocks at once it’s probably easier to just destroy the objects and check the list for null items and remove them.

for ( var i = blocklist.Count; i >= 0; i-- )
{
    if ( blocklist *== null )*

{
blocklist.RemoveAt(i);
}
}
Note: In this case you have to iterate backwards or you would skip one element each null item.