I’m generating a mesh at runtime to create terrain. Generating the mesh is running fine, mapping UVs is good, and the bounding box is working properly. However, there is a slight issue with there not being any kind of collisions.
It has a mesh collider attached to it, and the generated mesh is getting passed to the collider, however it is ignoring this mesh. I have also found that if i set the collider to Convex in the unity editor then change it back the collider works as it should. I have tried changing the collider to convex in the code, but this doesn’t seem to do the same thing as clicking the check box. This says to me that there is some function call that takes place when you check the box in the editor. Since I can’t very well click this check box in the finished game, does anyone know about this? I’ve seen other people dynamically generating mesh colliders with no trouble, but none of them have mentioned this issue.
When looking into this, I noticed that the bounds on my new meshCollider was zero area. I tried to set the bounds on the meshCollider, but it didn’t work. I investigated further.
Then RecalculateBounds won’t actually do anything. Setting the bounds directly also won’t change the bounds on myMC even if it changes it on myMC.sharedMesh.
To set the bounds on myMC properly, you must assign myMC.sharedMesh after the mesh has been created an populated with vertices.
I used sharedMesh to create the new mesh, so that’s not an issue.
I noticed that clicking any of the following on and then off enables the new mesh collision to work (IsTrigger, Smooth Sphere Collisions, Convex). Apparently, there is some sort of initialization done by the Editor with this clicks that allows it to work.
// Assigns an arbitrary mesh collider to the current transform
var meshToCollide : Mesh;
if(!meshToCollide) {
Debug.LogError("Assign a mesh in the inspector");
return;
}
transform.gameObject.AddComponent(MeshCollider);
transform.GetComponent(MeshCollider).sharedMesh = meshToCollide;