Deleting single Triangle from Mesh
I currently try to delete a single triangle from a mesh in unity. The mesh is an Icosphere that I created using ProBuilder. Now I want to delete one triangle to have a "hole" into the sphere.
This is my code for doing so:
private void DeleteTriangle(int id) {
var currentMesh = _meshFilter.mesh;
var triangles = currentMesh.triangles.ToList();
triangles.RemoveAt(id + 0);
triangles.RemoveAt(id + 1);
triangles.RemoveAt(id + 2);
currentMesh.Clear();
currentMesh.vertices = vertices.ToArray();
currentMesh.triangles = triangles.ToArray();
currentMesh.RecalculateNormals();
}
But when running this code somehow 2 triangles end up getting deleted and I cant figure out why exactly. I am running this code on id 0, so in the array only the 0th, 1st, and 2nd element should get removed but I still end up with this:
Answer by OlivierHoel · Oct 02, 2019 at 04:02 AM
RemoveAt() will effectively change the size of your triangle list, so you have to be careful when calling it consecutively. Your code should be:
triangles.RemoveAt(id);
triangles.RemoveAt(id);
triangles.RemoveAt(id);
or
triangles.RemoveAt(id+2);
triangles.RemoveAt(id+1);
triangles.RemoveAt(id+0);
You should be able to figure out why by yourself ;)
Oh my god I am so stupid. I overlooked that completely. Thank you!
This answer is accurate and super helpful. One thing I noted is that I was trying to optimize a mesh by deleting triangles that had an edge length of zero, and just deleting the triangle levels the vertices in place, which is probably not what you want unless all the vertices are shared by the surrounding triangles. I found that running
currentMesh.Optimize();
actually removes the vertices that are no longer connected to any triangle and appropriately reorders/updates the mesh data to reflect the new state. I'm not sure if this is 100% the best way to do it and there may be cases where this doesn't work, but it was pretty effective for my purposes.
Your answer
Follow this Question
Related Questions
Getting face of mesh when you already have one tri 0 Answers
Can you fit meshes together from Blender to create terrain in Unity? 2 Answers
How To Find Meshes Without Normals for Global Illumination? 2 Answers
Blender meshes disappear from project after reopening 0 Answers
Scale and Rotation Problem for Mesh 0 Answers