Unity gets the text width method of the Text component

First add a ContentSizeFitter component on Text , and then select the Horizontal Fit property as Preferred Size. (This representative will adapt to the actual width)

You can see that the Width property of RectTransform turns gray at this time. You can try to modify the displayed text content, and the Width of the Text will automatically change with the length of the text.

At this time, the sizeDelta.x of the RectTransform obtained through the script is the width of the text at this time. When you just add to the scene and modify the text content, you need to call SetLayoutHorizontal of ContentSizeFitter first , so that the width will be refreshed in real time, otherwise the width may be incorrectly obtained.

this.fitter.SetLayoutHorizontal();
RectTransform rect = this.text.GetComponent<RectTransform>();
Debug.Log("width is " + rect.sizeDelta.x);

One thing to note is that if you want to get the correct width, you must ensure that the active attribute of the Text node and all its ancestor nodes is true, otherwise the width will be 0.

Guess you like

Origin blog.csdn.net/shaobing32/article/details/122970292