'Is it possible to make a triangle on a mesh transparent at runtime?

I have a procedurally generated plane mesh in Unity. I am sending raycasts at runtime which will collide with particular triangles in the mesh, and am getting the index of the triangle using RaycastHit's triangleIndex field.

I want a triangle to become transparent when the raycast hits it at runtime. What would be the best way to do this?



Solution 1:[1]

Alright, I figured it out. While this does create garbage triangles, you could just set the appropriate tris to be 0, which means that the three vertices of the triangle will point to the vertex at index 0.

var tris = mesh.triangles;
tris[idx] = 0;
tris[idx + 1] = 0;
tris[idx + 2] = 0;
mesh.triangles = tris;

Since accessing and resetting mesh.triangles is computationally expensive, I also stored the mesh's triangles at startup. That way, I don't need to access mesh.triangles to change it.

Solution 2:[2]

you could get the gameobject or mesh renderer; then either disable the mesh renderer on it or disable the whole gameobject.

[SerializeField]
private MeshRenderer obj;


// in your other function you would then run after the raycast hits
obj.enabled = false;

if it had a box collider that you still wanted you wouldn't disable the whole object

Solution 3:[3]

You would have to access the mesh's triangles, change that array so the triangle your trying to make transparent is actually removed from the mesh, afaik this is the only way.

var tris = mesh.triangles;
tris[yourTriangle] = null;
mesh.triangles = tris;

Sorry am not able to test this code.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vikram B
Solution 2 Blahblah
Solution 3 Mad Hatter