I’m working on a project where several clients connect to a server. A set of minigames can be played. For the requirements of the project, the minigames are instantiated and destroyed when they are started and quit. I noticed there was a bad material leak (and therefore memory leak) going on, but I couldn’t find anything in my code.
Turns out that I was using the bloom post processing effect on the cameras of the minigame prefabs. All image effects of the standard package derive from PostEffectsBase, which has a CreateMaterial() method. It however does not have a DestroyMaterial() function - all materials that are created are never cleaned up. In regular games this might not immediately seem like an issue because normally you just have one camera throughout the game, but the memory leak also affects the editor. The editor keeps all those materials in memory, so when repeatedly starting and stopping the game, the image effects garbage materials keep piling up. You can see this very clearly in the memory profiler - just start the game repeatedly in the editor and watch the number of materials increase.
The solution is simple: add an OnDestroy() in all image effects you’re using, and clean up the materials created by the image effect using the following method, defined in PostEffectsBase():
protected void DestroyMaterial(Material material)
{
if (material == null)
return;
#if UNITY_EDITOR
DestroyImmediate(material);
#else
Destroy(material);
#endif
}
I was surprised to find no other mention of this when Googling the issue - hopefully this thread might be of use for future developers running into this issue.