- Home /
Change a material color
Hello, I'm trying to find a specific material on an object and its children and alter its colors based off of sliders. This is the code I have so far but it doesn't work. Thank you for your help.
public void ChangeColor(float rvalue, float gvalue, float bvalue)
{
//Color materialcolor = new Color(rvalue,gvalue,bvalue,1);
materialcolor.r = rvalue;
materialcolor.g = gvalue;
materialcolor.b = bvalue;
foreach(Renderer part in r)
{
allmaterials = part.renderer.sharedMaterials;
//materiallength = Renderer.sharedMaterials.Length;
//allmaterials.Length;
materiallength = part.renderer.sharedMaterials.Length;
for (int i = 0; i < materiallength; i++)
{
if (allmaterials[i].ToString() == "malenude-skin")
{
allmaterials[i].color = materialcolor;
}
}
}
}
It didn't work but I didn't want to forget the code so I just commented it out until I could figure out how to make it work.
Answer by Berenger · Mar 23, 2012 at 06:08 PM
First, from the doc :
"It is not recommended to modify materials returned by sharedMaterial. If you want to modify the material of a renderer use material instead."
Second, part.renderer is unnecessary, like part.renderer.renderer. It's correct, but it requires one more GetComponent. Just use part.
Third, the override ToString() of Material inherit from UnityEngine.Object and will give you the name of the GameObject, I'm not sure that's what you want. HasProperty might more appropriate.
Finally, check how r is created. Maybe it's just initialized.
Yes r is initialized further up in the document. I will give this a shot later and post back with results.
Okay so if I use the HasProperty function to check if it has material by name "skin", then changed the base color of the material. How can I get that to work.
HasProperty only checks if it has a material with the property of color but I need a specific material
Your answer
![](https://koobas.hobune.stream/wayback/20220613065435im_/https://answers.unity.com/themes/thub/images/avi.jpg)