I have a game object that has multiple materials (count of 3-4) and I would like to set the color of all those materials the same. How do I do this?
myObj.material.SetColor("_Color", Color.red);
CodePudding user response:
there is .material but also .materials
Material[] materials = myObj.materials;
for(int i = 0; i < materials.Length; i )
{
materials[i].SetColor("_Color", Color.red);
}
myObj.materials = materials;
As @derHugo pointed out, you need to clean up those materials if you destroy the object, like in OnDestroy
If you want to apply the color-change to all objects using these materials, then sharedMaterial is your friend (same Behaviour as editing a material in the Inspector):
Material[] sharedMaterials = myObj.sharedMaterials;
for(int i = 0; i < sharedMaterials.Length; i )
{
sharedMaterials[i].SetColor("_Color", Color.red);
}
myObj.sharedMaterials = sharedMaterials;
Same procedure, but you don't need to clean up, but it changes all instances.
There is also MaterialPropertyBlocks which can be useful, especially in combination with DrawMeshInstanced (when you want to have a TON of objects with different colors)