Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Determine Text Line Count and Characters Per Line

Discussion in 'UGUI & TextMesh Pro' started by kromenak, Mar 25, 2016.

  1. kromenak

    kromenak

    Joined:
    Feb 9, 2011
    Posts:
    266
    When using the Unity UI Text component, is there a way to determine the number of lines of text, and the number of characters per line of text?

    The Text.cachedTextGeneratorForLayout seems really promising - it returns a list of UILineInfo objects, which each tell you the start and end char index for the line.

    However, the info I get from Text.cachedTextGeneratorForLayout is always 1 line...even if, visually, I can see that the text wraps to 3-4 lines. It seems like it only returns multiple lines if there are explicit line breaks - not if the text is implicitly wrapped due to the size of the rectTransform.

    Has anyone found a good way to do this? I have a script that adds spacing between the letters, but adding spacing causes the layout to be incorrect. So, in the preferredWidth property, I'm trying to calculate an updated preferredWidth for the rectTransform. What I have works well for single line text, but when it wraps to multiple lines, it doesn't work correctly.
     
  2. pfreese

    pfreese

    Unity Technologies

    Joined:
    Feb 23, 2015
    Posts:
    85
    Use Text.cachedTextGenerator instead. The cachedTextGeneratorForLayout version will internally change flags like horizontal wrapping and vertical overflow to determine the maximum boundaries of text. The cachedTextGenerator property will give you information about the way the text is actually laid out.
     
  3. DaveCrowdStar

    DaveCrowdStar

    Joined:
    Nov 13, 2015
    Posts:
    13
    Can we get some insight into how this works? Here is my exact code:


    Code (CSharp):
    1.  TextGenerationSettings settings = textComponent.GetGenerationSettings(new Vector2(width, 0));
    2. return textComponent.cachedTextGeneratorForLayout.GetPreferredHeight(s,settings);

    For some reason this is slightly off. Sometimes there are two lines, but the preferred height thinks there are 3 lines of text. Each line of text is taller by 2 pixels than the actually text line displayed in the editor.

    My goal is to know the size without instantiating a GameObject. That way I can know how much space to give something in a scroll view containing thousands of elements.

    Maybe I have the wrong strategy? If there is a better way to achieve my goal, I am interested.