Changing mesh collider at run time

Hi there, I’m having some issues with my mesh collider. During run time I’m changing the vertices and I want to update the mesh collider to match the visual changes of the mesh.

Visibly the mesh is changing, but the collision volume is remaining as it’s original shape - I’m using mesh.RecalculateBounds() to update the collider after I assign the updated vertices back to the mesh (I believe that’s the correct approach) but this doesn’t seem to work.

Any suggestions?
Thanks!
Ant

You have to set the collider mesh to null and then assign the updated mesh.

This doesn’t seem to work anymore. Destroying and recreating the meshcollider does.

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

I have tried all solutions out in Unity 2017.2.0f3 but none worked. Here is my observation and solution:
If you assign a “used” mesh like this:

var newMesh = ProceduralGen.GetNewMesh();
DestroyImmediate(this.GetComponent<MeshCollider>());
var collider = gameObject.AddComponent<MeshCollider>();
collider.sharedMesh = newMesh;

it won’t work for some reason. However, in my case, when I assigned the procedurally generated Mesh straight to the collider’s sharedMesh, it worked:

var collider = gameObject.GetComponent<MeshCollider>();
collider.sharedMesh =  ProceduralGen.GetNewMesh();

Also, in this case you don’t have to worry about the order in which you assign the meshFilter and collider’s meshes. Plus, there is no need to remove and add the collider! This is definitely not the best solution for those of you who have to deal with heavy, complicated procedural generation, but in my case it worked fine. Hope this helps!

For me the answer was that I needed to switch the order I was calling functions

Before

  1. Create Mesh
  2. Added Mesh Collider
  3. Populated mesh with triangles

After

  1. Create Mesh
  2. Populate Mesh with triangles
  3. Add Mesh Collider

var smr = _renderer;
var mc = _collider;
var colliderMesh = new Mesh();
smr.BakeMesh(colliderMesh);
mc.sharedMesh = null;
mc.sharedMesh = colliderMesh;

Most practical solution here suggested by defaxer:

Workd for me.
Just get the

myGamObject.GetComponent<AnyCollider>().gameObject.SetActive(false then true again);

For Unity 2019.1.1f1 this method seems to work for me:

public MeshFilter newMesh; //the mesh you want to replace the old one with

public void ChangeMesh()
{
        meshFilter = GetComponent<MeshFilter>();
        meshFilter.mesh = newMesh.sharedMesh;
        GetComponent<MeshCollider>().sharedMesh = newMesh.sharedMesh;
}

//Note: if you select the object in the inspector while the game is running, unity will change your mesh back to it's initial value