- Home /
Question by
jeroen11dijk · Dec 14, 2014 at 08:59 AM ·
gameobjectprefabcolour
Change the colour of a prefab with a script.
I have an public gameobject pickup. Then in an if statement I have picpup.renderer.material.color= Color.red. I want my pickup to be a couple of cubes, which is a prefab and are together in an empty gameobject. If I put the prefab as the public gameobject the texture will be non existing turning everything pink. If I put the empty gameobject as public gameobject it gives an error stating that it does not have a renderer. So my question is how can I do it for all cubes.
Comment
Best Answer
Answer by SkaredCreations · Dec 14, 2014 at 12:03 PM
Since you have more renderers then of course you must loop through all renderers in its object tree. The following code will assign the color Red to all materials to all renderers of the current object:
Color newColor = Color.red;
Renderer[] renderers = GetComponentsInChildren<Renderer>();
foreach (Renderer r in renderers) {
foreach (Material m in r.materials) {
if (m.HasProperty("_Color"))
m.color = newColor;
}
}