- Home /
UI: Horizontal layout of many dynamically-sized Text and Buttons?
Hi all, I want to make a UI that shows a sentence of text, where each word is its own UI element, so I can do effects on individual words (like tween and colour them). Additionally certain words are buttons, the user can click on them to change their content (and it could swap in a word that's much longer than what was there before). Think like an interactive storybook that pulses words as they're narrated.
I've been able to make this using old-school TextMeshes and resizing boxcolliders for buttons, but now I've got to swap over to the new Unity UI system.
Right now my approach is something like this:
I attach Words and ButtonWords to an object on the Canvas. It has Horizontal Layout Group and Content Size Fitter components.
each Word has a top level Layout Element component with a preferred width (200) and flexible width, and a child Text object (for the content), with a Content Size Fitter
each ButtonWord is like a Word, but with an extra child for the Button.
What I usually see is that the spacing of each word looks like it doubles each time. eg. "The Quick Brown Fox" appears as "The.Quick..Brown....Fox".
This is doing my head in :) Do I have to adjust the preferred width of each Word's LayoutElement after i've assigned text (with a rule like 10px per character)? Or should the Content Size Fitter handle that?
Any advice is greatly appreciated!
Thanks.
Answer by brikim13 · Apr 16 at 03:03 PM
If your contents' size changes then yes I would try setting the "preferred width" after assigning text. Unity's tool doesn't do a great job when it comes to dynamically laying out children contents.
Are you trying to do something like the following?
If so you can try out using my script. I had the same issue with positioning the UI contents, so I created some tools for it and I think it maybe able to help you too. https://github.com/briankim13/UnityUIHelpers
Your answer
Follow this Question
Related Questions
I need help in making a GUI layout scroll view 3 Answers
2 dialogs not displayable at the same time. 2 Answers
EditorGUILayout.Foldout seems to stop working past indent 3 0 Answers
4.6 UI.System: Triggering Layout Rebuild help 2 Answers
Trouble creating a horizontal group for Tall and Wide screen orientation! 0 Answers