KOSOY
KOSOY

Reputation: 31

Unity - getting the correct text size after Content Size Fitter

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: enter image description here

Expected to get real height after LayoutRebuilder.ForceRebuildLayoutImmediate(); and Canvas.ForceUpdateCanvases();

But it didn't help

Upvotes: 1

Views: 1029

Answers (1)

Simsalabimson
Simsalabimson

Reputation: 21

It is a bit of a hacky solution, but you could try to wait for one frame, until you try to get the correct height. The easiest way of achieving this would be to use Coroutines.

private IEnumerator HeightUpdateAfterOneFrame()
{
  yield return null; 

  // Get height
}

Upvotes: 0

Related Questions