Removing Tris from mesh on click

Currently Im am trying to remove the Triangles of the portion of a mesh that has been clicked on by the player.
This is what my Current Script looks like:

function Update(){
	if(Input.GetMouseButtonDown(0)){
		Shoot();
	}
}

function Shoot(){
	var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
	var hit : RaycastHit;
	if (Physics.Raycast (ray, 100)) {
   		print ("Hit something");
   		
   		var mesh : Mesh = transform.GetComponent(MeshFilter).mesh;
		var verts = mesh.vertices;
		var tris = mesh.triangles;
		mesh.Clear();
		tris = removeTriangle(hit.triangleIndex, tris);
		mesh.vertices = verts;
		mesh.triangles = tris;
		transform.GetComponent(MeshFilter).mesh = mesh;
	}
}

private function removeTriangle(triangle : int, tris : int[]) : int[]{
	for (var i = triangle*3; i < tris.Length-3; ++i) {
		if (tris[i] == -1) break;
		tris[i] = tris[i+3];
	}
	return tris;
}

Help would be much appreciated.

Regards,
Anthony Faraci

1 Like

What is it you’re asking for help with? I assume something is going wrong with it and you need assistance figuring out why.

I’m no UnityScript expert, so I’d start by making sure that your verts and tris variables are being assigned copies of the mesh data rather than pointers to it, otherwise when the mesh is cleared you’ll end up with pointers to empty data.

It’s been a while since I’ve done this, so I cant remember for sure, but don’t you also need to call mesh.Apply() or something along those lines to update the GPU vertex buffers? This might be what you’re trying to do with line 20, but I’m not sure if re-assigning the mesh reference will trigger that.

The code looks mostly OK except for the fact that you don’t pass the RaycastHit to the Raycast function. If you change it to

if (Physics.Raycast (ray, hit, 100)) { ...

…then I think it will work.

Ohh wow, i didnt even notice this.