Problem removing bones from a SkinnedMeshRenderer at runtime

Hi,

I am having an issue removing bones from a SkinnedMeshRenderer at runtime. I am combining skinned meshes to improve performance and I have that working just fine- however I’d like to be able to remove the meshes I previously combined at runtime. I am able to update the triangle and vertex arrays just fine, but when I try to update the bindpose and bones array I get the following error: “Number of bind poses doesn’t match number of bones in skinned mesh”. That seems like a pretty straight forward error, but when I print out the length of the bindpose and bone arrays, they are the same, so I don’t know why I’m getting that error. If this is a bug in the engine is there some workaround? If not, can someone tell me what’s wrong with the code below? Thanks.

public static void RemoveInstanceFromCombinedMesh( SkinnedMeshRenderer combinedMesh, CombinedMeshInstanceInfo instanceToRemove){

        Mesh mesh = combinedMesh.sharedMesh;

        //...There is some code here to remove triangles and vertices

        //RemoveArrayIndices is a helper function that returns a new array with a range of indices removed from the source array
        Transform [] newBones = (Transform [])RemoveArrayIndices(combinedMesh.bones, instanceToRemove.startBoneIndex,instanceToRemove.boneCount);
        Matrix4x4 [] newBindPoses = (Matrix4x4 [])RemoveArrayIndices(mesh.bindposes, instanceToRemove.startBoneIndex,instanceToRemove.boneCount);

    
        Debug.Log("New Bones length: " + newBones.Length);
        Debug.Log("New BindPoses length: " +  newBindPoses.Length);


        //OUTPUT:
        //New Bones length: 3
        //New BindPoses length: 3

        
        //These lines cause an error even though the lengths are the same:
        //Number of bind poses doesn't match number of bones in skinned mesh

        combinedMesh.bones = newBones;
        mesh.bindposes = newBindPoses;

}

I figured out a solution. Apparently I am not supposed to modify sharedMesh directly. Instead I made a copy of sharedMesh and made modifications to that and the error went away.

Mesh newMesh = (Mesh) UnityEngine.Object.Instantiate(combinedMesh.sharedMesh);

//modify mesh
			
combinedMesh.sharedMesh = newMesh;
1 Like