Home > Back-end >  How can I find the line count and characters per line for textmeshpro in Unity?
How can I find the line count and characters per line for textmeshpro in Unity?

Time:08-18

I'm trying to figure out the number of characters per each line in a multi-line text inside Unity. I'm using textmeshpro instead of text component to display text on my canvas. Also, I want to count the number of lines that is displayed within the viewport. I'm currently using scroll view and textinfo.lineCount gives me the number of lines of the whole text rather than just the text that is visible in the viewport. I'd appreciate it if someone can help me out here.

CodePudding user response:

Assuming that the TMP_Text changes its size depending on the text you can try the following:

float viewportHeight = viewport.GetComponent<RectTransform>().rect.height;
int lineCount = textinfo.lineCount;
float textinfoHeight = textinfo.GetComponent<RectTransform>().rect.height;
float heightOfLine = textinfoHeight / lineCount;
float visibleLineCount = viewportHeight / heightOfLine;

Notice that visibleLineCount is a float, because a line could be cut off by the viewport. Also this approach assumes that the lines are all the same height in the TMP_Text. If you use markdown stuff this won't work.

  • Related