- Home /
Materials Count creates Memory Leak
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
Answer by DMGregory · May 22, 2014 at 06:11 PM
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.
Answer by Xumbu · May 20, 2014 at 10:16 PM
use Equals() to compare strings (sry java background)
try
renderer.materials = new Material[1]; renderer.material[0] = Green;
tried renderer.material = new $$anonymous$$aterial(Green);
but it seems to double the material count
does renderer.materials store the extra materials to change between them
I'm not sure but it seems like the material 'setter' just adds the material to the array.
and probably material 'getter' returns the first element of this array. otherwise i can't explain that problem.
try it out
Thanks, I don't know why but this seems to be happening to me with the materials all the time now