- Home /
Change a property of a material and effect all Gameobjects using that material
I've got a material I'm using for a number of gameobjects. Is it possible to change the Main color alpha value for this shared material and have it effect all other gameobjects using the same material.
I've tried like this, but this just creates an instance of the material which is affected.
public void ObjectOneTransparency (float value) {
Vector4 tempCol = object1.material.color;
tempCol.w = value;
object1.sharedMaterial.SetColor("_Color",tempCol);
}
Whats really frustrating is the when the game is running you can edit the the main color alpha just by clicking on color and this effects all gameobjects.
.................................................................................. ..................................................................................
For anyone reading this, a workaround which works is to just create a public Material in your script and then simply adjust values of this , which will effect all other objects using this material.
public Material matOne;
public void ObjectOneTransparency (float value) {
Vector4 tempCol1 = matOne.color;
tempCol1.w = value;
matOne.color = tempCol1;
}
Answer by Arshia001 · Mar 20, 2014 at 07:17 PM
The reason for this is that Unity instantiates every material at run-time so that you DON'T modify every object with the same material. The solution to that would be to use sharedMaterial instead of material:
object1.sharedMaterial.color = Color.black;
sharedMaterial is the (non-instantiated) material you actually assigned to your object. I don't know what happens if you modify the sharedMaterial and then modify the material instance on some objects though, so be cautious how you use it.
Oh and one more thing: $$anonymous$$odifying shared$$anonymous$$aterial actually modifies your material asset (the one you have created in your project) and any changes will be saved along with your project and will be present the next time you run your game. $$anonymous$$eep in $$anonymous$$d that modifying shared stuff (shared$$anonymous$$aterial, shared$$anonymous$$esh, etc.) is generally a bad idea.
(Sorry about the double answer, can't post comments tonight for some reason)
Answer by SirCrazyNugget · Mar 20, 2014 at 07:44 PM
You've got the right idea using sharedMaterial but when you do
Vector4 tempCol ...
you're creating a new material, just use
Vector4 tempCol = object1.sharedMaterial.color
or (Color tempCol)
Worth emphasizing: using material
in code works differently than everything else. Just looking at renderer.material
copies the shared material, and hooks the gameObject to that.