Unity C# , get text width / font character width

user3578286 picture user3578286 · Nov 10, 2016 · Viewed 7.2k times · Source

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 .

Answer

Umair M picture Umair M · Nov 10, 2016

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.