- Home /
Make children of a Layout Group fit their respective sizes (confusing docs)
I'm trying to use Horizontal Layout Group with Text children that dynamically change their width to match the text content. The recommended approach from the docs is to avoid Content Size Fitter: https://docs.unity3d.com/Manual/HOWTO-UIFitContentSize.html
This part of the docs makes no sense to me as they don't explain how to actually make the children fit their content size:
You can’t put a Content Size Fitter on each child. The reason is that the Content Size Fitter wants control over its own Rect Transform, but the parent Layout Group also wants control over the child Rect Transform. This creates a conflict and the result is undefined behavior.
However, it isn’t necessary either. The parent Layout Group can already make each child fit the size of the content. What you need to do is to disable the Child Force Expand toggles on the Layout Group. If the children are themselves Layout Groups too, you may need to disable the Child Force Expand toggles on those too.
The most simple example with Text children:
Canvas
-> Panel (Horizontal Layout Group with Child Force Expand Width off)
-> Text
-> Text
-> Text
As you'd expect, there is nothing telling the Texts to fit content sizes so they do not. Going against instructions and putting a Content Size Fitter on each child does actually seem to work, but you need to ignore the warning box and also force a layout after loading the scene.
I'm loath to go against the docs and put in hacks to force layouts. Has anyone else encountered this?
Answer by MechEthan · Jan 04, 2019 at 08:23 PM
If you're running Unity 2017.2 or higher, keep "Child Force Expand Width" unchecked, and then check the "Child Controls Size Width" box.
For versions older than that, I can't remember, but you can avoid a Content Size Fitter per child. I remember it being a huge pain though.