Instantiate SkinnedMeshRenderer.sharedMesh copy, need to call Destroy?

Hi, I am doing the following:

private Mesh mesh;

private void Awake()
{
    var skin = GetComponent<SkinnedMeshRenderer>();
  
    mesh = Instantiate(skin.sharedMesh) as Mesh;
    // modifying mesh in some way...
  
    skin.sharedMesh = mesh;
}

private void OnDestroy()
{
    // Do I need to destroy the mesh or will Unity take care of it when the SkinnedMeshRenderer is destroyed?
    Destroy(mesh);
}

I’ve seen some Unity editor crashes since writing this code and I am not sure if it’s a coincidence or if it’s because I am double-destroying the mesh. Do I need to destroy this mesh copy myself or will the SkinnedMeshRenderer do it for me?

Also, the “sharedMesh” property itself is confusing. I have multiple SkinnedMeshRenderers that are each being modified in this way, what is even being shared that justifies calling it a “sharedMesh”?

Unity will take care of it during garbage collection - as long as no other references to the Mesh remain. It should be safe to leave it alone and not Destroy() it.

You sure about this? Unity makes you explicitly destroy materials or render targets that you instantiate so I’m wondering what would make the mesh any different in this case.

Materials will garbage collect as well - render targets you do need to explicitly free (although I have a feeling they may GC as well actually – it just might take a couple of frames before the lock is released)

I will note - in your example, you maintain the reference as a private variable in the class (“mesh”) – if you want it to be freed, make sure to assign null to it; otherwise the reference will keep it alive.