How to get the width of UI Text with Horizontal Overflow?

I’m looking for a way to get the width of a new UI Text width Horizontal Overflow = Overflow. I need the width to position other objects (like custom Image bullet points at the start of a centered text line) according to the with of the text. The Width of the RectTransform is unchanged when the text displayed is wider than the RectTransform size.

This function will allow you to determine the size of any particular character, in a given font. You can create a loop to go through your string and add up all the character widths.

(but I think you will be better off with the suggestion posted in the comment, by mmmpies, about how to expand the rect transform automatically. Had no idea about that option myself, thanks Pie.)

You can get the width of the text in the limits of the RectTransform of his own GameObject via scripting by using:


It works if you have the “horizontal overflow” option set.

If you want to uncheck it, then you will need to enlarge the RectTransform or the text will wrap to more than 1 line and you will get the width of the set of lines instead : this can be done using a “Content Size Fitter”, as explained in the other answers.

Maybe you’re doing it the wrong way. You’re getting the width of the text because the width doesn’t change when the text overflows, but there’s a way to make it change according to the text width (so the overflow configuration is not needed). Add a “Content Size Fitter” component to the same game object with the Text component, and set “Horizontal Fit” to “Preferred size”. The gameObject’s size will change according to the pivot, set pivot.x to 0.5 and it will be centered.

This way the width will change, so you just have to set the image as a child game object of the text, and place it at the start.

There are some other small issues with this - the rect does not update until the next render frame, and as a result you can’t do sub-string positioning things. I’m trying the font.GetCharacterInfo approach, but there’s a lot to worry about. Not as simple as just adding char-widths together.


 public static float GetSizeOfWord(Text text, string word)
        float width = 0.0f;
        CharacterInfo charInfo;
        foreach (char c in word)
            text.font.GetCharacterInfo(c, out charInfo, text.fontSize);
            width += charInfo.advance;

        return width;

^ This is not quite right. I don’t exactly know whether to use .advance or .glyphWidth

I’m also going to try changing the text, and forcing the text meshes to update using “Canvas.ForceUpdateCanvases()”, and then sampling the size, but this could be a huge performance hit on a large canvas.