How to get the size of a UnityEngine.UI.Text for which I *just* changed the text?

So I have the following on a game object: Text component and ContentSizeFitter component set to “Preferred size”. I am trying to: set the text field, then measure it so I can dynamically position it properly.

void SomeFunc(){
    Text t = GetComponent<Text>();
    t.text = "some new string";
    // Get the size of the text
    // Then do some calculations
    // Then reposition the text.rectTransform.position.

I have tried using Text.rectTransform.sizeDelta, but that is the size of the LAST string displayed (I think the ContentSizeFitter needs a frame to update). I also tried using LayoutUtility.GetPreferredWidth/Height, but that returns 0.

How can I get the displayed size of that Text component right away?

Use GetPreferredWidth and GetPreferredHeight of TextGenerator.

    TextGenerator textGen = new TextGenerator();
    TextGenerationSettings generationSettings = m_myTextBox.GetGenerationSettings(m_myTextBox.rectTransform.rect.size); 
  float width = textGen.GetPreferredWidth(newText, generationSettings);
  float height = textGen.GetPreferredHeight(newText, generationSettings);

The RectTransform may not update until the end of a frame, but I’ve seen an immediate change in the value I get when calling LayoutUtility.GetPreferredHeight(transform). This will tell you how tall the Text would be if it were able to overflow all of its vertical content. Try:

Debug.Log(LayoutUtility.GetPreferredHeight(transform) + " vs " + transform.rect.height);
text.text = e.text;
Debug.Log(LayoutUtility.GetPreferredHeight(transform) + " vs " + transform.rect.height);

Where transform is a RectTransform and text is a Text.

I know this is an old thread but one way to force Canvases to update is to use Canvas.ForceUpdateCanvases().

// Set the dialogue.
textRT.GetComponent<Text>().text = data.dialogue;

// Update the canvases to get the updated rect of the text.

The Rect of the TextComponent will now be updated. Keep in mind that this forces all canvases to update their layout.

Yeah you right. Text size (preferred width && height) applied to the next frame.

LayoutUtility.GetPreferredWidth/Height paired with a ContentSizeFitter component set to “Preferred size” will return 0 if the object is not active in hierarchy. I have tested this with Unity 5.6.0f3.

In order to get the displayed size of that Text component right away you need to make sure that the gameobject is activeInHierarchy just before calling LayoutUtility.GetPreferredWidth/Height