I’ve created a lot of objects which shares the same material, so I’m using sharedMaterial for them.
But in some occasions i need some of them to have a different material, like a highlight in that object, which changes the material.
so I can change it by change that single object to use material instead of shared material.
but after I finish the highlight options, I set the object to sharedMaterial again.
so its something like it:
pass1 - awake: go.renderer.sharedMaterial.SetColor(“_Color”, color);
pass2 - during the highlight: go.renderer.material.SetColor(“_Color”, highlight);
pass3 - end of the highlight: go.renderer.sharedMaterial.SetColor(“_Color”, color);
So I got two questions:
does the instance of the pass2 is leaked in the memory, since i don’t have its reference anymore?
in case of leak, if I save the reference of that material, and use Resources.UnloadAsset(ReferenceOfmaterialInPass2) after it’s done, does it will unload that material from memory without any killing the whole performance in some android/ios devices?
Assuming it works just like ‘mesh’ and ‘sharedMesh’ on MeshFilter, step 2 will create a clone. Step 3 will then modify the clone - it doesn’t restore the original material. Then next time you execute step 2, it should not create a new clone. Use the profiler to make sure though. You can also check whether the objects you get from querying ‘material’ and ‘sharedMaterial’ match before/after operations like steps 2 and 3 - then you’ll see when they get cloned.
If you want to be more in control of the cloning, I’d consider creating the “highlighted” material on startup, then switching objects back and forth by just assigning to sharedMaterial. This will avoid creating any new materials after startup.
In any case, if you have orphaned materials which are not referenced by any objects any more and want to destroy them, you can call Resources.UnloadUnusedAssets - though this is rather slow.