How can I change transparency of multiple child objects by their parent object?

Is there easy way to change multiple child objects transparency by writing some line of code in the parent object?
The problem is when I change the child objects alpha and then I add another child object to the parent object, the new child object his alpha is not change, so I need to change his alpha again.

Is there a way I can change the parent alpha even if he doesn’t have any sprite renderer or something?

Thank you in advance.

1 Like

You can put this code on the parent and it will set the alpha of all the children:

public void setAlpha(float alpha) {
    SpriteRenderer[] children = GetComponentsInChildren<SpriteRenderer>();
    Color newColor;
    foreach(SpriteRenderer child in children) {
        newColor = child.color;
        newColor.a = alpha;
        child.color = newColor;
    }
}

There is no built-in way to know when an object has set a new parent. You would need to add code wherever you call “SetParent” or "transform.parent = " and tell the parent to update either directly or through an event or something.

1 Like

I thought maybe to use canvas as the parent object, so every time I want I can change his alpha, and it will basically solve the problem, I think…

If these are all UI objects we’re talking about, you can use a Canvas Group on the parent to change the alpha of the whole child hierarchy.

7 Likes

OnTransformParentChanged() callback does this exactly, and maybe more pertinent to OP’s use case, OnTransformChildrenChanged() would notify the parent that it’s child transforms have changed. I think (and with a little testing or help from the community) this only reflects direct descendants but I could be wrong (wouldn’t be the first time).

I was not aware of those callbacks, and somehow didn’t find them when searching. Thanks.

Although considering his last post, I’m not sure he’ll need to handle hierarchy changes if he’s using UI objects.

You’re welcome. I wasn’t aware of them until fairly recently either, which led me to scour the docs for any other gems I hadn’t known about. There’s quite a bit, though none other that I currently have use of.

add “Canvas Group” component on your Parent. You can set alpha value by"Canvas Group" for all children

2 Likes