How do you set up Unity’s UI Layout system so that the chat bubble changes in size automatically based on the length of the text? What’s the right use of Layout and Content Size Fitter elements?
To achieve this behavior you need to attach a Content Size Fitter to text component, a Layout Group and Content Size Fitter to background. But this setup is not good for things like chat performance wise. Try to set sizeDelta of background to width and height of text.
Something like this:
_backgroundRectTransform.sizeDelta = new Vector2(_textMeshPro.rectTransform.rect.width, _textMeshPro.rectTransform.rect.height);
You might want to wait for end of frame or call _textMeshPro.ForceMeshUpdate() for text to build geometry.
thanks, but the idea is that the text rectTransform will expand based on the text entered, like in a mobile messages chat bubble. would you still have to apply some layout components to the textmeshpro for the resizing?
Yes, size fitter will shrink/expand text rectTransform and you only need to grab it’s width and height and assign them to background rectTransform. And no, there will only be Content Size Fitter attached to text with both axis set to preferred size. No other layout stuff. Just listen to TMPro_EventManager.TEXT_CHANGED_EVENT for changes to get text rectTransform size. Check out Examples & Extras project, “23 - Animating Vertex Attributes” scene.
But, if you really want to use layout system, you’ll have to attach a layout group and a size fitter to _each background image transform to react to changes of text transform size, which also need a size fitter to shrink/expand. Also text should be a child of background.
I like just having the UI layout system manage everything
Have you tried both approaches / are there pro’s cons? In general, I don’t always use TMP and use plain UI Text, since they require creating font materials etc.