How to change the height of a button according to the height of the text in it?


How would you do if you had a vertival layout composed of buttons and you wanted:

  • the witdth of the buttons to be the same witdth as the vertical layout
  • the height of each button to be driven by the text inside it

The solution has to work by code as I create each elements by script.

I have tried to follow the doc but it does not work:

I tried to use “contentSizeFitter”
I tried to use “LayoutElement”
I tried to use a vertical or horizontal layout on each buttons and desactivate childforcesWidth
I tried a lots of more stuff.

I run unity 2020.3.24f1 LTS on windows

Even manually I cannot seem to find a system that works.


Thanks in advance.

You need to add a content size fitter to the buttons as well, if you’re adding different shapes of text, so the button will fit the size of the text component. Try to explain better how you’ve set up these objects, with pictures and such, so I can have a better idea of how you’re doing things

There is a contentsize fitter both on the TMPUGUI and the Button
It looks fine before play and when i press play it acts wierdly.
When I tweak the values of the vertical layout, eg the padding, it gradually turn back to normal.

The problem seem to come to the content size fitter on the button but I did not find a better way to get this setup working.

I am trying to think that I am going to need to code my own grid system. Seems ridiculous.