I have a vertical layout group containing 3 game object
when I try to get the correct position of the child Objects from the vertical Layout group, it does not giving the correct output.
I tried
myPosition = this.gameObject.transform.localPosition;
myPosition = this.gameObject.transform.position;
myPosition = this.GetComponent<RectTransform>().position;
myPosition = this.GetComponent<RectTransform>().anchoredPosition;
Non gave the correct output. How to get this
CodePudding user response:
You just need to fetch the position in Update
or LateUpdate
method, don't do that in Awake
or Start
.
void Update()
{
if(transform.hasChanged)
myPosition = ((RectTransform)transform).anchoredPosition;
}
https://docs.unity3d.com/Packages/[email protected]/manual/UIAutoLayout.html
The rebuild will not happen immediately, but at the end of the current frame, just before rendering happens.
According to the documentation above, you cannot freely trigger layout rebuild, so this way is just based on the order of layout calculations: Call these 4 methods before fetching the position.
// VerticalLayoutGroup vlg;
vlg.CalculateLayoutInputHorizontal();
vlg.SetLayoutHorizontal();
vlg.CalculateLayoutInputVertical();
vlg.SetLayoutVertical();
myPosition = ((RectTransform)transform).anchoredPosition;