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?
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.
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).
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.