Search code examples
unity-game-enginemeshmesh-collider

Unity : can I change the shape of a mesh collider at runtime?


I have a mesh that updates it's shape according to the user's input, how can I get the collider to match the new shape of the mesh ?

As an important note : the mesh is always always convex ( no exceptions ). I saw that it is important in order for the collider to work properly.

I have found the following video that does it here but the collider is simply erased and recalculated for each frame by doing meshCollider.sharedMesh = null and then meshCollider.sharedMesh = updatedMesh.

Since I am already calculating the position of each vertex, edge and triangle of my mesh, is it possible to me to use those values for the mesh collider ?


Solution

  • No way to do it as colliders do not have constructors for this. What you are doing is explicitly frowned upon in unity docs

    'You should not modify mesh geometry that is used for colliders because the physics engine has to rebuild an internal mesh collision acceleration structure every time you change the mesh. This causes a substantial performance overhead. For meshes that need to collide and change at runtime, it is often better to approximate the mesh shape with primitive colliders like capsules, spheres and boxes.'

    One work around is to use InvokeRepeating on your method and create the new mesh collider every second instead of every frame (you can test and make it 0.1 second , 2 second, whatever can run without frame drops). You can call CancelInvoke when the object is done shifting.