Modify Mesh Collider when modifying vertices?

I am modifying vertices on some objects in my scene, but if they have a Mesh Collider on them, that collider retains the original shape.

I think this is because it is still tied back to the original Mesh, which is in essence, a prefab for the mesh component.

Is there a way to make a unique collider for a modifed mesh?

Shouldn’t setting MeshCollider.sharedMesh to your new mesh be enough? :wink:

setting meshcollider=null and then meshcollider=mesh seems to work in unity 4

			mc = go.GetComponent<MeshCollider>();
			if(mc==null)
				mc = (MeshCollider) go.AddComponent (typeof(MeshCollider));
			else
			{
				mc.sharedMesh = null;
				mc.sharedMesh = mesh;
			}

Not really an elegant solution, but disabling and then enabling MeshCollider works fine for me

Yes, but it’s slow. I used to do this when I was using mesh colliders for my voxel terrain. If anyone else have a better answer, then I’ll vote you up!

void Update()
{
    if (chunk.Rebuild(mesh))
    {
        Debug.Log("Rebuilt mesh");
        DestroyImmediate(collider);
        gameObject.AddComponent<MeshCollider>();
    }
}

Basically, you need to destroy the collider and add it back on again.

Just nulling the mesh and resetting it doesn’t seem to work anymore. I had to destroy the whole collider and recreate it.

DestroyImmediate(this.GetComponent<MeshCollider>());
var collider = this.AddComponent<MeshCollider>();
collider.sharedMesh = myMesh;

As the other posts have noted, a) re-enabling the Mesh Collider component or b) reassigning the mesh to the collider both seems to work.

But maybe you are wondering: why is this happening in the first place?? I will admit that this is a bit speculative, but I would imagine that changing the vertices using something like ---- exampleMesh.vertices = exampleVertices; ---- loads the new vertices to the GPU but not to RAM. I would imagine that this happens by default because some engineer at Unity decided that, most of the time, it would be unnecessary to upload changes to vertices both to the GPU and RAM.

My best guess is that re-enabling the meshCollider component || reassinging the mesh to the meshCollider will reupload the mesh data to RAM without costing too much overhead. Both are good solutions!