- Home /
Why does reading MeshRenderer.material change MeshRenderer.sharedMaterial?
I am trying to lookup materials by name and set a texture. My first attempt was
if(renderer.material.name == "My Material")
renderer.material.SetTexture(newTex);
... then I noticed the " (Instance)" attached to the material's name (e.g. renderer.material.name == "My Material (Instance)"). So my second attempt was
if(renderer.sharedMaterial.name == "My Material")
renderer.material.SetTexture(newTex);
... this works... the first time.
Unfortunately the second time I call my function I noticed that the renderer.sharedMaterial's name is now equal to "My Material (Instance)". In other words, after any call to renderer.material the renderer.material == renderer.sharedMaterial.
Can somebody explain this? Once I access renderer.material how can I access the original renderer.sharedMaterial? Shouldn't sharedMaterial always point to the original shared material?
I'm wondering the same thing, there's no reason why reading the alpha of material should suddenly create a new instance. Any more thoughts on this? I'm trying to avoid creating material instances here while I animate various body parts in a character, so when the alpha is 1, I check if the material's alpha is 1 already before trying to modify it, but that check defeats my purpose and does create an instance. Doesn't make sense.
Answer by roamcel · Sep 07, 2011 at 09:26 AM
This is actually a "buglike" feature, which you can identically reproduce for other self-iterating 'types' like prefabs (and their transforms in particular). In your case, newtex creates a new instance of the material, and thus changes the reference!(brain freeze). http://answers.unity3d.com/questions/159889/brain-freeze-declaring-a-prefab-inside-the-same-pr.html
You can work around it with something like
newTex = myparent.newTex;
immediately after you instantiate the object. But it's quite probable that you'll need to refactory a bit to avoid headaches.