Get text width for UnityEngine.UI.Text


I have situation in which I have 3 (or more) transforms that have Text component, and I have “change language” method. When I run this method, Text.preferredWidth changed, but not in the current frame. I cant use ienumerators, because now by default this gameobjects is inactive.

I want to create some “temporary” text, in which I want put new, localized, text, and get preferredWidth of it, but I can`t understand what I’m doing wrong.

var go = GameObject.CreatePrimitive(PrimitiveType.Sphere);
go.GetComponent<Text>().text = "some text";
var width = go.GetComponent<Text>().preferredWidth;

The last line print: 0

I’m new in Unity, and I can`t now imagine, how I can solve this issue. Any help? Thanks!

UI components do work like that, they are not updated on the go, but rather in a bulk at the end of a frame. Never really delt with this problem myself, but I the most upvoted answer in this question looks really promising.

Also, one thing that bugs me in your code is the GetComponent overusage, you actually don’t need any here. AddComponent also returns that component, so all you have to do is

var text = go.AddComponent<Text>();

and then use that text variable instead of calling GetComponent which is an expensive call.