- Home /
Change Color of Material without Calling Component
I am trying to change the color of a material and have it affect ALL components without have to call every component.
I am currently using: Renderer rend = GetComponent(); rend.material.shader = Shader.Find("Standard"); rend.material.SetColor ("_Color", Color.black);
This is working well - However, I have about 100 components that all use the same material that needs to be changed on a button click.
Is there a way that I can set a global variable so I can change the color of all components using the material?
Answer by gamer87 · Sep 01, 2016 at 09:17 AM
Hi @GMVRDev
if you are using the same material for all the 100 components, then if you change the material property, it will apply to all the 100 components.
you could make
public Material mat;
OnButtonClick()
{
mat.color = Color.red;
}
I tried your suggestion however I got the error UnityEngine.$$anonymous$$aterial does not contain a definition for 'color'.
Is there more that needs to be added to this?
You tried to use it as a method when it is a property which you use with the assignment operator (=) material.color = color;
Also, the problem with your first code was that using renderer.material
instantiates the material assinged to the renderer. You can use renderer.shared$$anonymous$$aterial
to get the material shared by all the renderers. If the material is an asset the changes made to it will stay after exiting playmode.
I hope that 'Paint_Body' is a material and not gameObject or other objects... And you could see that, you are not at all using the assignment operator (=) ..
Answer by Ardaaytac · Sep 01, 2016 at 08:32 AM
Get the gameobjects which has that special component. After that change their color on start function.
For example:
void ChangeColor()
{
foreach (MyScript item in GameObject.FindObjectsOfType<MyScript>())
{
item.gameObject.GetComponent<MeshRenderer> ().material.color = Color.red;
}
}
just did this with cubes.
@Ardaaytac - I implemented your suggested code - it applied to all of the items that had my C# code added as a component! Thank you for your suggestion!
Your answer
![](https://koobas.hobune.stream/wayback/20220612091905im_/https://answers.unity.com/themes/thub/images/avi.jpg)