unity中rect变换的位置UI

Position of rect Transform in unity UI

我在使用 Unity 的 UI rectTransform 进行编程时发现了一个非常令人困惑的问题:

在检查器中,我们可以发现RectTransform的位置被设置为(0,0,0)

但是在Start()中的代码中,当我打印位置时:

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

这将给我一个职位:

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

当我们尝试获取 position 而不是 localPosition 时,事情会更加混乱:

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

我也在playMode期间检查了这个rec​​tTransform的posX和posY,表明它没有被改变(一直显示(0,0,0)

这有什么问题吗?

您在 RectTransform 组件中看到的不是本地位置。手册说:

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

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

在您的例子中,您有一个非拉伸矩形变换。因此,尝试打印锚定位置:

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

减少混淆并更好地理解更改 RectTransform 如何影响在脚本中看到的值的一种方法。 (例如,场景/检查器设置的变化如何反映在脚本成员变量中)

  1. 创建单独的检查器 属性 window:单击 RectTransform 中的 3 个点和 select“属性...”
  2. 打开调试模式:在应该弹出的新window中...点击最高级别的3个点为整个window和select“调试” 您现在可以使用具有 RectTransform 的对象并查看调试 window 中的成员变量(与脚本中可访问的相同变量)如何显示您的更改。