Hello, I’ve noticed this issue and can’t figure out if this is due to my coding or unity bug. I change the material on the object a lot and my materials count increases and increases.
Here’s my sample code
if(renderer.material.name != Green.name + " (Instance)")
{
renderer.material = Green;
}
this is in my update function.
This would happen every time I highlight it but it this seems to increase the count. Does anyone else had this problem, if so how did you solve it. Thank you
Note that unlike most other objects, Material instances are not automatically disposed when no gameObject/component is using them.
Anytime you create a material instance through script (which happens automatically whenever you use renderer.material instead of renderer.sharedMaterial), cache a reference to it, something like this:
_cachedMaterial = Instantiate(sourceMaterial) as Material;
renderer.sharedMaterial = _cachedMaterial;
If you later change to a different material or destroy the renderer, and won’t need _cachedMaterial again, manually dispose of the instance (since this instance was created through script, you won’t get a “Destroying assets is not permitted” error):
Destroy(_cachedMaterial);
(Use DestroyImmediate if this is an Editor script)
This will prevent material instances from leaking.
If you don’t need to change parameters on the material per-instance, use renderer.sharedMaterial instead - this will allow multiple objects to share one material reference, rather than instantiating a unique copy for each one.