Physics.BakePhysXCollisionMeshData Performance Drop

I’m baking Colliders in a job using a scheduled job, which has minimal performance impact

[BurstCompile]
public struct BakeMeshCollidersJob : IJobParallelFor
{
    [ReadOnly]
    public NativeList<int> MeshIds;
    public void Execute(int index)
    {
        int meshId = MeshIds[index];
        Physics.BakeMesh(meshId, convex: false);
    }
}

However, when I set the mesh to the gameobject’s collider

_meshCollider.sharedMesh = Mesh;

I get a serious lag spike
image
What am I missing here? Why does assigning a mesh with a baked collider cause PhysX to go crazy.
Any advice is most welcome, thanks!

Docs have this to say:

Note: When you add a MeshCollider component to a GameObject with a MeshFilter component already present, the sharedMesh property is set automatically and this might trigger a re-bake.

Maybe that’s it?

Yeah, I think that’s what’s happening, but it also seem to be the case that if I start with MeshCollider shared mesh and MeshFilter shared mesh set from the start, and I update the mesh data, this also triggers a rebake.

I can’t seem to find any way of updating a mesh without the collider auto-rebaking, but I want to bake manually in a job…

There must be a way otherwise Physics.bakeMesh wouldn’t exist lol

Some additional details, I’m updating the mesh with

        mesh.SetVertexBufferParams(verts.Length, descriptors);
        mesh.SetIndexBufferParams(indices.Length, IndexFormat.UInt16);
        mesh.SetVertexBufferData(vertArray, 0, 0, vertArray.Length, stream: 0, meshUpdateFlags);
        mesh.SetIndexBufferData(indexArray, 0, 0, indexArray.Length, meshUpdateFlags);
        mesh.SetSubMesh(0, meshDescriptor, meshUpdateFlags);

I’ve tried
-keeping the meshfilter and meshcollider shared meshes assigned and updating the mesh
-setting meshfilter and meshcollider to null, baking mesh colliders, re-assigning submesh
-activating gameobject before assigning meshCollider shared mesh
-activating gameobject after assigning meshCollider shared mesh

They all result in the PhysX lag spack.

I should note that I’m not certain if this lag is unity baking the colliders, or doing something else…

Hmm… still completely stumped on this one.

I can’t seem to find any way to prevent Unity from Baking mesh colliders automatically when assigning the mesh collider’s shared mesh. :frowning:

Alright, I think I’ve finally figured it out.

In the docs

he MeshCollider component reuses the baked mesh if, and only if, all of the following conditions are met:

The MeshCollider's cookingOptions are exactly the same as were specified during baking

It looks like for Physics.BakeMesh, the default cooking option is not MeshColliderCookingOptions.None. Therefore, even though I had specified on the mesh collider

 meshCollider.cookingOptions = MeshColliderCookingOptions.None, 

I still needed to add it to the Baking

Physics.BakeMesh(meshId, convex: false, MeshColliderCookingOptions.None);