I'm trying to make an OK/Cancel-style dialog which will expand to fit its text in Unity 5.6. I've been trying to pull this off using Unity's built-in UI layout components, but so far I haven't been able to get it exactly right.

The dialog has a background, a title, a body, and two buttons. The goal is for the dialog to resize itself vertically to fit the length of the text. Here is an example with placeholder graphics:

enter image description here

I have this almost working properly, but I created it by abusing the built-in layout components and it doesn't always behave properly. Here's how it's currently set up:

  • Background is an Image
    • Vertical Layout Group:
      • Control Child Size: Width
    • Content Size Fitter:
      • Horizontal Fit: Unconstrained
      • Vertical Fit: Min Size

Background has the following children:

  • Title is a Text
  • Body is a Text
    • Content Size Fitter
      • Horizontal Fit: Unconstrained
      • Vertical Fit: Preferred Size
  • Buttons is a GameObject
    • Horizontal Layout Group
      • Child Force Expand: Width and Height

This setup works about 90% of the time, with the dialog properly resizing according to the text. However, at certain (seemingly arbitrary) body lengths, an extra blank line will be added to the Body text, which disrupts the vertical spacing and gives the dialog a strange look:

enter image description here

This isn't too surprising, because you're not supposed to put a Content Size Fitter on a child of a Layout Group; however, I couldn't figure out any other way to get the dialog to vertically expand to fit more text. Is there a better way to handle this?


You can use the text object's preferredWidth and prefferedHeight values to do this.

I've done something similar in a project here:


My code includes a value for creating a ratio in the end result's width and height, but if you are only expanding the height, all you need to do is call SetSizeWithCurrentAnchors vertically and it should expand to the necessary height.

Some of the operations I perform, however, are due to scene setup and the background image I use. Be aware of such things when it looks arbitrary.


Perhaps you could set the "body" component to have the text verically aligned to the center. Therefore, even if there's a blank line, the text appears on the center anyway.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.