I have been noticing my memory increment to absurd levels in my game. I decided to run the profiler to look at how memory is being managed. I noticed something peculiar.
When my scene is loaded, I have around 1000 meshes (that is what the profiler says). I then do something in my game that adds a LOT of meshes (this is expected). My mesh count goes up to 3000. After that, I delete the game object containing all of those new meshes, via the editor. I expected meshes to go back down to 1000, but instead it stayed at 3000?
I repeated the test; pushing my mesh count to 5000. Deleted that game object, and it stayed at 5000. The same thing is happening with materials as well.
It is worth noting that the “GameObjects in Scene” count is correctly going up and down. The mesh and materials counts however never go down DESPITE deleting the gameobjects they are attached to in the editor.
What could cause this to happen?
EDIT:
I dug a little deeper and looked at a sample of the data in detailed view. I have a LOT of meshes showing up here with NO REFERENCES:
1 Like
So as it turns out, the problem arose from the use of SkinnedMeshRenderer.BakeMesh()
I was creating a single compound object out of MANY smaller segments. As a post process, I bake them all into a single mesh for use in a collider. This was causing my to have thousands of orphaned meshes somehow. Here is the culprit:
public void Bake() {
List<CombineInstance> combineInstances = new List<CombineInstance>();
Mesh buffer;
CombineInstance cInstance;
foreach (RoadComponent component in components) {
buffer = new Mesh();
component.meshRenderer.BakeMesh(buffer);
cInstance = new CombineInstance();
cInstance.mesh = buffer;
cInstance.transform = component.meshRenderer.transform.localToWorldMatrix;
combineInstances.Add(cInstance);
}
// bake
Mesh baked = new Mesh();
try {
baked.CombineMeshes(combineInstances.ToArray());
baked = MeshUtility.SolidifyMesh(baked, 0.1f);
baked.Optimize();
} catch (Exception e) {
throw new Exception("Issue while combining mesh segments: " + e.Message);
}
collider.sharedMesh = baked;
}
For each call to BakeMesh(), the buffer mesh was being orphaned. In order to fix this, one must explicitly destroy the buffer mesh:
Destroy(buffer);
I made a small example project to test this out, and this is indeed the culprit.
This almost feels like a bug. At the very least, this should be documented!