Im generating meshes procedurally in my engine, they render fine and even interact with a character controller properly.
However when i try to raycat onto them to find a colission point on the surface I get really wierd results. Sometimes its fine, but sometimes the cast returns a hit, but at a location that isnt on the mesh. If i obscured tha cast with another object (a default cube for eg) the cast wil report hitting the cube accuratey, but it i remove the obstruction the cast reports an erroneus hit on the procedural mesh in a location that isalong the cast line but can be many units short of the actual mesh. I cant track down what is happening with this at all.
Im letting unity rcalculate my normals for me and then assigning the mesh to the shared mesh member of the collider
Updating the sharedMesh of a Collider does not update it…
Here is the code (C#) I’m calling from time to time to update a mesh:
// get mesh
MeshFilter meshFilter = GetComponent("MeshFilter") as MeshFilter;
Mesh mesh = meshFilter.mesh;
mesh.Clear(); // clear mesh because vertices count changed
// init arrays
Vector3[] vertices = new Vector3[new_nb_vertices];
Vector3[] normals = new Vector3[new_nb_vertices];
// compute the new vertices and normals here...
// then assign the new vertices and normals to the mesh:
mesh.vertices = vertices;
mesh.normals = normals;
mesh.RecalculateBounds(); // useless if triangles have been assigned
// and finally update the collider mesh
MeshCollider meshCollider = GetComponent("MeshCollider") as MeshCollider;
meshCollider.sharedMesh = mesh; // DOES NOT WORK!
The mesh is updated when rendered, but any RayCast hits the initial mesh (the one that was computed the first time).
I could solve this problem by creating a new Mesh instead of updating the old one:
Mesh mesh = new Mesh ();
MeshFilter meshFilter = GetComponent("MeshFilter") as MeshFilter;
Destroy(meshFilter.mesh);
meshFilter.mesh = mesh;
But now the problem is that the memory increases each time I update the mesh…
Thanks a lot Tzan!
I added the line: meshCollider.sharedMesh = null; before: meshCollider.sharedMesh = mesh; and now it’s working fine.
Have a nice day!