Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 595
itsPav Avatar asked Oct 17 '25 08:10

itsPav


2 Answers

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

like image 133
Sov3rain Avatar answered Oct 18 '25 22:10

Sov3rain


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 !
like image 39
gmspacex Avatar answered Oct 18 '25 20:10

gmspacex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!