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
Here it is what i am telling about: