Position of rect Transform in unity UI

armnotstrong picture armnotstrong · May 2, 2017 · Viewed 18.7k times · Source

I found a very confusing issue in programming with Unity's UI rectTransform:

in the inspector, we can find that the RectTransform's position was set to (0,0,0) enter image description here

but in the code in Start(), when I print the position:

parentObject = transform.parent.gameObject;
Debug.Log("parentObject rectTransform :" + parentObject.GetComponent<RectTransform>().localPosition);

This will give me a position of:

parentObject rectTransform :Panel: (0.0, -562.5, 0.0)
UnityEngine.Debug:Log(Object)
NewWorkerController:Start() (at Assets/Scripts/NewWorkerController.cs:60)

Things will be even more confusing when we try to get the position instead of the localPosition:

parentObject rectTransform :Panel: (621.0, 1365.5, 0.0)
UnityEngine.Debug:Log(Object)
NewWorkerController:Start() (at Assets/Scripts/NewWorkerController.cs:60)

I have also checked the posX and posY of this rectTransform during playMode which indict that it has not been changed(kept showing (0,0,0))

What's wrong with that?

Answer

Hellium picture Hellium · May 2, 2017

What you see in the RectTransform component is not the local position. The manual says :

Positioning the UI element

A UI Element is normally positioned using its Rect Transform. If the UI Element is a child of a Layout Group it will be automatically positioned and the positioning step can be skipped.

When positioning a Rect Transform it’s useful to first determine it has or should have any stretching behavior or not. Stretching behavior happens when the anchorMin and anchorMax properties are not identical.

For a non-stretching Rect Transform, the position is set most easily by setting the anchoredPosition and the sizeDelta properties. The anchoredPosition specifies the position of the pivot relative to the anchors. The sizeDelta is just the same as the size when there’s no stretching.

For a stretching Rect Transform, it can be simpler to set the position using the offsetMin and offsetMax properties. The offsetMin property specifies the corner of the lower left corner of the rect relative to the lower left anchor. The offsetMax property specifies the corner of the upper right corner of the rect relative to the upper right

Source : https://docs.unity3d.com/Manual/HOWTO-UICreateFromScripting.html

In your case, you have a non-stretching Rect Transform. Thus, try to print the anchored position :

parentObject = transform.parent.gameObject;
Debug.Log("parentObject rectTransform :" + parentObject.GetComponent<RectTransform>().anchoredPosition);