unity-game-engine

How to get exact text width from horizontal overflow: wrap?


In Unity, I tried to get a size of text component, not TMP, which has horizontal overflow: wrap and vertical overflow: overflow.

When the text amount was out off the rect width and a new line is added, text.preferredHeight works properly. It returns the lined height.

But text.preferredWidth returns a wrong value. It wroks like the horizontal overflow is just overflow, no matter what it is indeed.

I want to get a value that the wrapped lines are applied.

chat.text = 'looooooooooooooooooooooong word'; //text is wrapped. Extra line is created
Debug.Log(chat.perferredWidth); // returns wrong value. Extra line is not applied
Debug.Log(chat.perferredHeight); // returns correct value.

Solution

  • Actually text.preferredHeight will also give you a bigger value when some lines are truncated, you need to perform a simple comparison with the size of the rect transform:

    public static class UGUIExtension
    {
        public static float GetRenderWidth(this Text text)
            => text.horizontalOverflow == HorizontalWrapMode.Wrap ? 
               Mathf.Min(text.rectTransform.sizeDelta.x, text.preferredWidth) :
               text.preferredWidth;
    
        public static float GetRenderHeight(this Text text)
            => text.verticalOverflow == VerticalWrapMode.Truncate ?
               Mathf.Min(text.rectTransform.sizeDelta.y, text.preferredHeight) :
               text.preferredHeight;
    }