teaching machines

Weighted Distribution in Unity UI

Suppose you have a Horizontal Layout Group in a Canvas-based UI in Unity, and some elements in the group should expand but not others. Or some should expand at different rates than others. Checking the Width option of Child Force Expand on the group seems like it might do what you want, but you are wrong. How the Child Force Expand algorithm distributes out the space is undocumented, as far as I can tell, and I haven’t been able to reverse engineer what it does. Leave it unchecked.

Do check the Width option of Child Controls Size. This option is poorly named and documented. When unchecked, the size of each child is set by its RectTransform. When checked, the size of each child is determined by its Layout Element component. If this option is checked and the children are without Layout Elements, the children will collapse to their minimum sizes. So, check the option and add Layout Elements to the children.

On each child’s Layout Element, set the Flexible Width property accordingly. Widgets with equal weights will expand at the same rate if the parent has leftover space.

If any child has a weight of 0 or doesn’t have a Flexible Width checked, it will be assigned its minimum size. If you don’t like the default minimum size, assign it on the Layout Element.

It seems like you should be able to set the minimum size in other ways—like with a Content Size Fitter on the child—but I haven’t found this to work. This would be especially nice on buttons, whose minimum size should snugly fit around their text label. I don’t see why the minimum size can’t be automatically calculated.


Leave a Reply

Your email address will not be published. Required fields are marked *