I have constructed a mesh following this pattern:
- create a mesh filter, renderer, and collider
- assign vertices
- assign triangles
- assign uvs
- assign tangents
- call recalculateNormals
- assign mesh to filter
- assign mesh to collider
First question: If I build the mesh tangents incorrectly, will it affect the collider’s behavior in any way?
Second question:
After adding a primitive object (with rigidbody) above the mesh, running the project yields a strange result. The primitive falls and contacts the mesh collider, but doesn’t seem to follow the collider’s shape. It sits flat as if the collider had a plane across the top of it.
If I set smoothSphereCollisions on the mesh collider at run time, the primitive will immediately fall into the shapes of the collider as expected. If I set smoothSphereCollisions in the code, the collider acts as a plane until I uncheck the option at runtime.
Basically, the mesh collider acts like a plane until i make any runtime change to it, then it works correctly.
I hesitate to include code here since there’s a lot of it. I was hoping someone could infer a likely cause from my description. If that isn’t enough, I will pare down my code and come up with a postable example.
The thing I failed to mention was that the mesh is generated as a flat plane and then re-generated as the more complex shape. It turns out the mesh collider wasn’t being updated even though the mesh had been changed and re-applied. The solution was to nullify the sharedMesh property of the collider before setting it to the new mesh. I guess this was happening automatically when properties of the mesh were altered at runtime.
Mesh mesh = gameObject.GetComponent<MeshFilter>().mesh;
mesh.Clear(false); // clear the previous mesh
// rebuild mesh here
MeshCollider collider = gameObject.GetComponent<MeshCollider>();
collider.sharedMesh = null; // nullify the previous sharedMesh
collider.sharedMesh = mesh; // assign the new mesh to the collider