- Home /
How to change single material color of GameObject?
Hello! I need to change color of object's child color. So, this child has 3 materials, i need to change only one material's color. On this image you can see whole the object. In it has child "default" with 3 materials. I need to change Blue to red in script. I tried to make this using:
ramps[stageCount].transform.GetChild(0).GetComponent<Renderer>().material.SetColor("_Color", Color.red);
But this script changes White color: How to get "Материал.2"?
Answer by highpockets · Nov 20, 2020 at 08:18 PM
You are going to have to access the material array materials
. Iterate through them to find the one you want and then change the color:
Material[] mats = ramps[stageCount].transform.GetChild(0).GetComponent<Renderer>().materials;
for( int i = 0; i < mats.length; i++ )
{
//material name usually returns something like "material_name (Instance) so you you can use Contains like I did or use another way to identify it. Contains might not work if the other materials names contain the substring that you pass, but if you name them so they don't have this problem, you should be fine"
if( mats[i].name.Contains("material_name") )
{
mats[i].SetColor( "_Color", Color.red );
break;
}
}
Another option would be to use Renderer.Get$$anonymous$$aterials() to avoid generating excess garbage.
Your answer
![](https://koobas.hobune.stream/wayback/20220613020144im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
material.SetColor ("_EmissionColor", Color.white) 1 Answer
Material.SetColor and Material.color are not working properly 0 Answers
How to change or set the Ground and Sky Tint color of a Procedural Skybox through script? 1 Answer
setColor function not working as intended 1 Answer
Acessing Shader Properties in a object that has two materials 1 Answer