itsPav
itsPav

Reputation: 83

Unity UI TextBox Dynamic Height. How do I make it expand based on text amount?

What up.

I'm instantiating a textbox gameobject. Then filling it up with text.

Any way to make the textbox height dynamically change?

GameObject reply1 = Instantiate(replyText, transform.position, 
transform.rotation);
reply1.transform.SetParent(textArea.transform, false);
Text reply1text = reply1.GetComponent<Text>();
reply1text.text = gameRounds[roundCount].reply[0];

The width is fine, don't need to change it.

Upvotes: 4

Views: 17227

Answers (3)

Sov3rain
Sov3rain

Reputation: 51

I need to correct @gmspacex's answer, which is utterly wrong (the screenshot speaks for itself, showing a warning), for future reference. The correct way of setting a Text element with a dynamic height or width is clearly described here: Make children of a Layout Group fit their respective sizes

To summarize you just need to:

  1. Add a vertical layout group to the parent
  2. Add a ContentSizeFitter component to the same object and set Vertical Fit to Preferred Size
  3. Toggle ON: control child size width and height, child force expand width
  4. Toggle OFF: child force expand height

No shenanigans with toggling the component on and off. If you find some element being "squashed", just add a LayoutElement component and set the Min Height property appropriately.

screenshot of the correct way of setting up the vertical layout group component

Upvotes: 5

Tiny Brain
Tiny Brain

Reputation: 640

You can add the ContentSizeFitter component to the text gameobject, and then set Vertical Fit to the Prefered Size. This solution only controls the text box's height.

If you want to control the parent's height automatically, follow those steps.

  1. Add Vertical Layout Group to the Parent.

enter image description here

  1. Add Text gameobject as a child and add a Content Size Fitter component.

enter image description here

  1. Now try to change the text of the Text component in a script. You will notice that it doesn't work properly. You should manually update the parent's layout group.
{
     exampleText.text = "Text Example \n Test automatic height";
     Invoke("UpdateParentLayoutGroup", 0.1f);
}...

void UpdateParentLayoutGroup() {
     exampleText.gameObject.SetActive(false);
     exampleText.gameObject.SetActive(true);
}
  1. Enjoy Unity !

Upvotes: 2

ZayedUpal
ZayedUpal

Reputation: 1601

You can change the text box's Vertical Overflow settings to Overflow. It automatically increases the textboxes height based on text content.
enter image description here

Upvotes: 0

Related Questions