unity-game-enginetextmeshpro

How to get the number of lines displayed in a Textmeshpro - text (UI)?


So in my script I want to know how many lines are displayed in a Textmeshpro - text (UI).

public TextMeshProUGUI commentaryText;

Debug.Log("number of lines " + (commentaryText.text.Split('\n').Length - 1));

I tried something like above but it will only show the number of lines with a \n newline character, however I also want to know about lines that are caused by wraparound when they reach the limit of the textbox. Is there a way to get the number of lines that the user sees?

Any advice appreciated. Thanks

enter image description here


Solution

  • Basically you can access commentaryText.textInfo.lineCount to get the number of lines. What I did is that on a button click it logs the number of lines for a TextMeshPro I created, so I was able to test it:

    public TextMeshProUGUI textMeshPro;
    
    public void Click()
    {
        Debug.Log(textMeshPro.textInfo.lineCount);
    }
    

    Update for what you'd like from the comments:

    maskable text mesh pro

    You need to set the TMP to align to bottom and set the overflow to masking. Then you need a parent that has a mask component (I used the basic panel). The text that would go outside the size of the parent is hidden.

    I'm not sure what you'd like with the line count, but this will count the hidden lines as well. So in my example if you use the lineCount it will log 6.