Hi there,
I’m concerned about avoiding memory leaks when swapping the mainTexture on a gameObject. Eg…
renderer.material.mainTexture = newTexture;
In the docs it states if the renderer.material is changed it is the coder’s responsibility to delete the material (now non shared) from memory using the DestroyImmediate(renderer.material); line in the OnDestroy() call.
So my question is, does swapping the material.mainTexture class as changing the material? Do I need the OnDestroy() call if I only affect the mainTexture?
If so do I just destroy the texture on onDestroy, or the material or both?
Thanks experts!
Richard
Changing renderer.material creates a new scene material the first time you do it, so as to have a unique material for that object. So in this case it would be better to instantiate a material yourself, and assign that to renderer.material. Then you’d change whatever you need to in the instantiated material. That way you have a reference to this material and can destroy it easily.
–Eric
Hi Eric, thanks for the swift response 
That sounds a great best practice, but question wise, does changing the mainTexture force the whole material to be cloned (non shared)? If I ONLY change the mainTexture, does that class as changing the material? Does the responsibility to destroy the material fall to the developer, or does that only apply if the material is changed (not just the texture)?
Thanks!
Yes, the texture is part of a material. You can’t actually change the texture of an object; you must change the texture of a material.
If you load a new level, everything is cleaned up anyway. But if you never load any levels, then you need to manage that yourself, which involves using Destroy and Resources.UnloadUnusedAssets as appropriate. (Since Unity objects are not part of Mono and are not garbage-collected.)
–Eric
Oh, I learnt a lot from that answer, thanks so much for your time!
I didn’t realise Unity objects are not garbage collected.