Unity – Calculating Text Area Sizes and Resizing

UI Text components are quite a useful thing, here are some tips:

Need to resize the bounds to match your massive text?

  /// <summary>
    /// Resize a Text area so it is large enough in height to fit the text string you specify.
    /// </summary>
    /// <param name="goTextObject"></param>
    /// <param name="myString"></param>
    /// <param name="autoResizeRect">true and the rect is resized, false not changed (height is a return param)</param>
    /// <returns>height that was calculated</returns>
    static public float SetHeightOfText(GameObject goTextObject, string myString, bool autoResizeRect)
        // This is the height that the text would fit at the current font height setting (see the inspector)
        TextGenerator textGen = new TextGenerator();
        Text titleText = goTextObject.GetComponent<Text>();
        TextGenerationSettings generationSettings = titleText.GetGenerationSettings(titleText.rectTransform.rect.size); 

        float height = textGen.GetPreferredHeight(myString, generationSettings);

        if( autoResizeRect )
            // Resize the rect to the size of your text
            RectTransform rt = goTextObject.GetComponent<RectTransform>();
            rt.sizeDelta = new Vector2(rt.rect.width, height);

        return height;


What if you wanted to move another object to just below your text component?

Well you need to take into account the scale of the text too.

float height = textGen.GetPreferredHeight(myString, generationSettings);
RectTransform rt = productTitleGO.GetComponent<RectTransform>();
float height = myText.GetPreferredHeight(myString, generationSettings);
float worldHeight = height * rt.localScale.y;

// Use the worldHeight to offset your next object under the text component.