Buttons Change Size to Match Text Width

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.

Suggestions?

Have you considered doing something involving the Content Size Fitter component?

@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.

I’ve looked at that component and considered it, but what I would really like is to change the size of the Button Art.

This won’t actually work: unless the Text is a sub-object of the Image, it will block the ray-cast to the Button.

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.

1 Like

Ok, I must not have been understanding it correctly. I’ll give it a try in the morning.
Thank you

Ok, it looks like my problem was a lack of Layout Group. I’m using a Horizontal Layout Group and that’s working correctly.

Thanks for the help!

1 Like

First, your button hierarchy should look like this:
–Button
|-Text

Then

  1. Add Horizontal Layout Group to Text, set Children Control&Children Force Expand only Width, set Horizontal Fit to Preferred Size
  2. Add ContentSizeFitter to Text, set Horizontal Fit to Preferred Size
  3. Add Horizontal Layout Group to Button, set the same (especially the setting sequence) as Text
  4. Change the text, you will see the effect
    Tips: Must add layout group before content size fitter

I followed these steps, but to make it work I had to add the ContentSizeFitter component to the button.

2 Likes