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.
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;
Hello, I am having issue with this 2 years later, and none of these options work anymore, after my mesh changes, i want to update the mesh collider like this, and it doesnt work in unity5 anymore i guess... pls halp mesh.vertices = vertices; mesh.RecalculateBounds(); mesh.RecalculateNormals(); DestroyImmediate(this.GetComponent<MeshCollider>()); MeshCollider collider = gameObject.AddComponent<MeshCollider>(); collider.sharedMesh = mesh;
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!
var smr = _renderer;
var mc = _collider;
var colliderMesh = new Mesh();
smr.BakeMesh(colliderMesh);
mc.sharedMesh = null;
mc.sharedMesh = colliderMesh;
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
What is meshFilter? and sharedMesh? I don't know how I can make it work
theMeshCollider.mesh = null; theMeshCollider.mesh = theUpdatedMesh;
– HannesRGreat, thanks for the help!
– AntLewis