There's one thing in Unity that was really irritating me but I've finally managed to get it right. While Unity UI layouts are pretty sweet, they can also be quite tricky. I want to share this in case someone else runs into a similiar problem as it cost me a lot of pain.

So here's the thing.
You have a UI text object, it's content will be changing during the game and you want the size of the object to match the size of the text, but and that's the tricky part, you also need to set a max width and have the text break in another line when it reaches this point.

Sound simple, so what's the catch? Well, in Unity you can manually set the size of your object and it will keep this size regardless of the text length. So if you don't need any background for your text object, you can just set the width which is gonna be the max width and align the text to the center, but if you need the background this will not work out.

To get the object size match its content there's a thing called content size fitter, you set it to preferred size and it will do exactly what would you expect. Well, the thing is that there's no max width option to be set. So it will expand its size based ont he text length and eventually it will go beyond the screen viewport and will never break. Even if it's inside a layout that has a manually set width, it will ignore it.

As already said, if you don't care about the background just set the width of the max width, align the text to the center and add a content size fitter with only the vertical option being preferred. Using this option with a background would meant having the background full width even if the text is short. So how the heck get the result we need?

I Googled hard and couln't find any solution, nothing I've tried didn't work until I've finally found a recent thread with the beautiful piece of critical information. While it seems like the text needs to use the content size fitter to shrink, it turned out the solution is not to use it on the text at all. Here's the source if you want to check it yourself.

The solution

This is the basic structure box > box > text

Don't use content size fitter on your text object at all.
Both boxes will have vertical layout (not horizontal) where everything is unchecked except controll child size.

The first box (only this one) will have content size fitter with vertical fit as preferred.

And finally the first box will have the child aligment as upper center.

How it works

Okay, awesome! But how does this thing actually works? If you check the Unity documentation all it says is: Whether the Layout Group controls the width and height of its child layout elements.
It's not very clear what it actually means.

As this not as simple to explain I've found a great article focusing on this topic specifically, so if you're interested I would suggest to take a look at this article.