- Home /
Changing the color of all children in an empty gameobject
I have an empty gameobject with a bunch of sprites put into it to construct a monster. I want to be able to easily change the monster's color depending on some variables. Is there any easy way of changing all of the monster's color without having to change each individual sprite renderer? Something like adding a filter or renderer on top and doing a simple renderer.material.color = Color.red; code?
Thanks, I ended up using the foreach loop, it was not the best but it served its purpose.
Answer by UnityDevelopper · Jun 19, 2014 at 01:26 AM
this code is in c# (you didn't specify which language);
//if 3d
foreach(Renderer variableName in GetComponentsInChildren<Renderer>()){
r.material.color=Color.red
}
//if 2d with sprite
foreach(SpriteRenderer variableName in GetComponents<SpriteRenderer> ()) {
c.material.color = Color.red
}
Hope this helps
I know it should be obvious for most reading this, but you need to use actual colors, and be consistant with variable na$$anonymous$$g:
//if 3d
foreach(Renderer r in GetComponentsInChildren<Renderer>()){
r.material.color= Color.white;
}
//if 2d with sprite
foreach(SpriteRenderer sr in GetComponentsInChildren<SpriteRenderer>()) {
sr.material.color = Color.red;
}
Answer by Owen-Reynolds · Jun 19, 2014 at 03:59 PM
No. You can use one command which individually changes each child (UD's reply.) But there's no one place you can change that will do that.
If all the sprites had the same shared material, you could change that one color. But, I'm assuming they use different head/body ... textures, which means there's no way they can share mats.
Meshes aren't grouped by gameObject, so the "parent filer" idea isn't a thing. The system might draw all heads first, then all arms.
I think, in practice, you won't want to change them all to the same color anyway. A red monster might want the hands to stay the same, the head might look good tinted (1,0,0) red, but the chest looks better at (0.8, 0.2, 0.2) red, and the legs might need a texture swap. It might be better if each monster color has a Material for each body part, instead of just a color. That will allow you to set color and texture and shader for each colored body part. You'll still have to change them individually for each child.
That's Awesome!!! Is there anyway I can do this by switching each sprite so Cat ear for dog ear and so on. So that effectively I could Completely change what my character is by just switching out the sprites. Also Developing in c#. Thanks.