I would like to create buttons that change horizontal size to match the length of the text on them.
As far as I can tell, we cannot make the button art be a sub-object of the Text because then it will render in front of the Text
What I would like to do:
Set the Text.Text
Find the Text’s Width
Adjust the Button accordingly.
I’ve seen suggestions that Font.GetCharacterInfo could be used to find the Width of the Text, but it seems like this data should be accessible without having to calculate it again.
@Antistone is correct, adding a ContentSizeFitter component to the Button GO will automatically resize the RectTransform to the width/height of the text.
This includes if you set the text to overflow.
Do you mean you want to change the size of the button’s sprite but keep its clickable area the same? You could probably add another level to your object hierarchy, so the sprite is a child of the button but a parent of the text, and then use a content size fitter on the sprite but not the button.
You can prevent text from blocking ray-casts by adding a Canvas Group component to the text (and configuring it appropriately).
Text has to be a child object of the button, simply because the button has an Image (a graphic), the text is also treated as a graphic and no component can have two graphic based components on the same GO.
(Try adding a text component to the button GO and you’ll see)
If you want the text to automatically fill the button, with or without borders, then check the Text GO’s anchor settings.
Setting the width of a parent based on the size of a child is exactly what a ContentSizeFiter is for.