- Home /
MeshCollider is not getting updated when adding vertex to mesh
I have created a simple piece of code for adding vertices to a mesh by clicking on it. The vertex is added to the point of the mesh which is clicked. This works very well the first time. But the second time it fails to get the correct triangle from RaycastHit.triangleIndex. Here is the code, including a hack which actually makes it work. (The fact that the hack works also eliminates the possibility of this being a corrupted mesh.)
public void AddVertexScreenPos(Vector2 screenPos) { RaycastHit hit; if (HitScreenPos(Input.mousePosition, out hit)) { if (hit.collider.GetType() == typeof(MeshCollider)) { MeshCollider meshCollider = (MeshCollider)hit.collider; Mesh mesh = meshCollider.GetComponent<MeshFilter>().mesh; List<Vector3> vertices = new List<Vector3>(mesh.vertices); List<int> triangles = new List<int>(mesh.triangles);
vertices.Add(meshCollider.transform.InverseTransfo rmPoint(hit.point));
int[] triangleHit = GetTriangleIndices(ref hit);
triangles.Clear();
triangles.AddRange(RemoveTriangle(hit.triangleInde x, mesh.triangles));
for (int i = 0; i < triangleHit.Length; i++) { triangles.Add(triangleHit[i % triangleHit.Length]); triangles.Add(triangleHit[(i + 1) % triangleHit.Length]); triangles.Add(vertices.Count - 1);
}
mesh.vertices = vertices.ToArray(); mesh.triangles = triangles.ToArray(); mesh.RecalculateNormals(); mesh.RecalculateBounds();
//The following line should update the meshCollider, but it fails. //meshCollider.sharedMesh = mesh;
//Hack. This fixes the problem GameObject go = hit.transform.gameObject; GameObject.DestroyImmediate(meshCollider);
go.AddComponent<MeshCollider>(); //Hack end.
} }
}
Any suggestions?
Answer by MachineGunCat · Mar 15, 2011 at 10:47 PM
I know this is old but it showed up in Google when looking for a similar problem. User pkamat on the Unity forums solved this very same problem for me :
In place of your hack, try nullifying the mesh before assigning it your new mesh :
meshCollider.sharedMesh = null;
meshCollider.sharedMesh = mesh;
Source of the answer : http://forum.unity3d.com/threads/32467-How-to-update-a-mesh-collider
What he said.
Destroying and recreating a meshcollider component is far heavier than just assigning it the new mesh.
For some reason, meshcolliders don't like replacing meshes when they already have one... it will fail silently, and collisions won't work as expected.
Setting it to null first will let the meshcollider accept the new mesh.
Cheers
Your answer
Follow this Question
Related Questions
Mirror vertices procedurally 2 Answers
Save previous state of mesh procedurally 1 Answer
Generate a highpoly sphere with mesh collider procedurally 2 Answers
Selecting a single polygon / face at runtime 1 Answer
Hidden triangles and performance. 0 Answers