Unity C# , get text width / font character width

9k Views Asked by At

I want to get the width of a text in unity using C# .

Here is what I am trying to do .

int GetWidthOfMessage(string message)
{
    int totalLength = 0;

    Font font = text.font; //text is my UI text
    CharacterInfo characterInfo = new CharacterInfo();

    char[] arr = message.ToCharArray();

    foreach (char c in arr)
    {
        font.GetCharacterInfo(c, out characterInfo, text.fontSize);
        totalLength += characterInfo.advance;
    }

    return totalLength;
}

But font.GetCharacterInfo(...) returns false and characterInfo.advance is 0 for any character .

5

There are 5 best solutions below

3
Umair M On

Apart from your original question. Following the reason you are doing all this (expanding text box according to text content).

You can use Content Size Fitter component on your text object and set Horizontal Fit property to Preferred Size. And this will solve your problem.

Update:

Add Layout Element component as well and set preferred width value to 500 for example and set Horizontal Overflow property of text to Wrap. This will work fo sure.

1
Dylan Hart On

Try calling:font.RequestCharactersInTexture(c.ToString(), text.fontSize, text.fontStyle);

Before you call: font.GetCharacterInfo(c, out characterInfo, text.fontSize);

With the exception of '\t', I got every character I needed this way. (Probably better to request all the characters at once, though).

0
Yoann Haffner On

Maybe your font is dynamic: this means you have to add characters in your font, and you should use Font.RequestCharactersInTexture! This happened to me with a single UnityEngine.UI.Text component, no matter the font. Reference: https://docs.unity3d.com/ScriptReference/Font.RequestCharactersInTexture.html

0
BiN On

try use : font.RequestCharactersInTexture(c.ToString());

fontSize & fontStyle use default value.

and then use : GetCharacterInfo(char ch, out characterInfo info);

Then I got the right value of characterInfo.advance

0
zhiwei li On

I found Font.RequestCharactersInTexture(mStr, fontSize, FontStyle.Normal) is ok, but Font.RequestCharactersInTexture(mStr, fontSize, FontStyle.Bold) will get character.advance = 0