Getting the correct text size after Content Size Fitter

Hello everyone, please help, I can’t figure it out myself

I have a TextMeshPro Prefab

I wanted the height of the object to match the actual height of the text, so I added a Content Size Fitter component to the prefab and gave it a Vertical Fit - Preferred Size.

In my code, I create a GameObject from a prefab, then change the text in it, and then I want to get a new correct height value

But all the options that I try are wrong and I can’t do it in any way. Can you please tell me what I’m doing wrong and how can I get the correct value? Here is my code:

void createDialogItem()
{
    Instantiate(dialogItemText, contentScroll);
    TextMeshProUGUI dialogItemTextTMP = dialogItemText.GetComponent<TextMeshProUGUI>();
    RectTransform dialogItemTextRectTransform = dialogItemText.GetComponent<RectTransform>();
    dialogItemTextTMP.text = GetLineAtIndex(currentLineIndex);

    // These are my desperate attempts to make the best of what I have found on the forums.
    dialogItemTextTMP.CalculateLayoutInputVertical();
    dialogItemTextTMP.ForceMeshUpdate(true, true);
    dialogItemTextRectTransform.ForceUpdateRectTransforms();
    LayoutRebuilder.ForceRebuildLayoutImmediate(dialogItemTextRectTransform);
    Canvas.ForceUpdateCanvases();
    LayoutRebuilder.MarkLayoutForRebuild(dialogItemTextRectTransform);

    Debug.Log("LayoutUtility GetPreferredHeight: " +  LayoutUtility.GetPreferredHeight(dialogItemTextRectTransform)); 
    Debug.Log("TextMeshProUGUI preferredHeight: " +  dialogItemTextTMP.preferredHeight); 
    Debug.Log("RectTransform height: " +  dialogItemTextRectTransform.rect.height); 
    Debug.Log("RectTransform.sizeDelta: " +  dialogItemTextRectTransform.sizeDelta.y); 
}

As a result, none of the options give me the correct value :frowning:

Here it is what i am telling about:

Canvas UI update gets “applied” at the later part of the frame if need (aka : if marked as dirty) , there are mainly 2 solutions to this :

  • 1 : Force the layout rebuild immediately to get the correct dimensions after using the method LayoutRebuilder.ForceRebuildLayoutImmediate(RectTransform rect) (don’t abuse the method)
  • 2 : Wait until the end of the frame to retrieve the updated values (either get it on next Update tick or call a coroutine to wait until end of the frame)