- Home /
Getting the width of UI text inside a layout allways 0.
Hello, I simply want to get the width of an element inside a horizontal layout at runtime. Currently I always get 0.0, using RectTransform.rect or RectTransform.sizeDelta. The width is definitely not 0.
Any ideas what the problem is? Or how to bypass it to find out the width?
Answer by DiegoSLTS · Jun 07, 2015 at 01:05 AM
I just tested this and I guess you're getting the size on the Awake or Start method, but you have to wait one frame before getting the correct sizeDelta or rect of the elements. I guess the reason for this is that the HorizontalLayoutGroup component adjusts the sizes on the first frame after all the Start methods have been called.
Instead of the common "void Start()" method, use "IEnumerator Start()" method. It'll work just like the first one, but it's now a coroutine so you can yield for one frame. So, instead of this:
void Start() {
Debug.Log(GetComponent<RectTransform>().rect.width);
}
which prints "0", use this:
IEnumerator Start() {
yield return null;
Debug.Log(GetComponent<RectTransform>().rect.width);
}
Awesome! I ended up extracting my objects in a different empty, which ended up working. But your answer is very clear and clever :) I thought it may have been the Start(), but I wasn't aware of a way to call anything right after Start. This will definitely come in useful in other situations, thank you!
It works. $$anonymous$$y first 4 times finding width worked fine without this, but the 5th... nah. But they all work with the IEnumerator adjustment.
Your answer
Follow this Question
Related Questions
Incorrect RectTransform width value when trying to read child RectTransform width. 0 Answers
RectTransform Pivot Point in the new UI? 1 Answer
Force Unity UI element to refresh/update? 4 Answers
How to make a health bar in Unity 5? 0 Answers
Change RectTransform pivot without changing position 0 Answers