New Unity UI Text - determine how much of a string will fit before truncated

With the new Unity UI Text object, when configured to truncate vertically and wrap horizontally. How can I determine at what character the string will be truncated at? That is, regardless of kern, we don’t want to use fixed size characters.

I’m looking through the documentation, but a lot of the methods that look like they might go in the right direction of resolving this all just get documented as “Called by the layout system.” Real helpful there Unity…

I have a feeling I can use the ‘cachedTextGenerator’ for this in some way.

Anyone have any helpful information on this beyond the limited documentation in the unity API?

      Text textComp = GetComponent<Text>();
       TextGenerator t = textComp.cachedTextGenerator;
       string result = textComp.text.Substring( 0, t.characterCountVisible );
       Debug.Log( "Generated " + t.characterCountVisible + " characters" );
       Debug.Log( "Visible string is: " );
       Debug.Log( result );

Unfortunately, characterCountVisible always seems to be 1 short of whats actually displayed (counting spaces), unless the whole string is generated, in which case it’s correct

2 Likes

hrmm, maybe that property is returning the index of the last character showing…

Only thing about this is that I have to assign the string to the Text. I need to do this before assigning the text, so I can break it up, and place it in a queue to be shown at a later time.

I had a feeling TextGenerator had something to do with it though. I’ma decompile that bad boy and take a look at how that ‘characterCountVisible’ gets calculated.

Its calculated by vertex count

return Mathf.Min(this.m_LastString.Length, Mathf.Max(0, (this.vertexCount - 4) / 4));

Not sure why it subtracts 4, but if the whole string is shown, and you draw the gertex positions, theres 4 odd verts that have no use… more weirdness

You can use textgenerator.Populate & generatorsettings with any string and canvas area you want to calculate.