父对象后子对象的位置移动

Position Of Child Object Shifted After Parenting

对于我的 UI,创建的层次结构链如下

Emptypanel 包含一个脚本,该脚本在运行时创建 UI_A 并为自身创建父级 UI_A

GameObject UI_A= Instantiate(g);
UI_A.transform.position = transform.position;
UI_A.transform.SetParent(transform);
UI_A.transform.localScale = transform.localScale;

UI_A 还包含一个创建 UI_B 的脚本,它将自身附加到 UI_A

//script in UI_A
void Start () {

        //float width = GetComponent<RectTransform>().rect.width;
        //float height = GetComponent<RectTransform>().rect.height;

        Vector3 pos = transform.position;
        pos += new Vector3(offsetFromEdge.x, offsetFromEdge.y, 0f);

        _UI_B = new UI_B(transform, pos);

    }

并在 UI_B 构造函数中:

    public UI_B(Transform parent, Vector3 pos)
    {

        GameObject obj = new GameObject();
        obj.AddComponent<Canvas>();

        var comp = obj.GetComponent<RectTransform>();
        comp.pivot = Vector2.zero;
        comp.anchorMin = Vector2.zero;
        comp.anchorMax = Vector2.zero;

        obj.transform.position = pos;

        obj.SetParent(parent);
        obj.localScale = scale;

    }

因此,当 offsetFromEdge 为 (0,0) 时,UI_B 在它应该出现的位置看起来不错,就在 UI_A 的顶部,localPosition 为 (0,0,0)。然而,当我将 offsetFromEdge 的值设置为 (1,1) 时,UI_B localposition 变得异常巨大 (3611.xx, 3611.xx, 0);

这些值显示在 RectTransform 组件的 Pos X 和 Pos Y 上,我相信这与 UI_B 的 transform.localPosition.

相同

我不知道是什么导致了这种行为。

您首先设置游戏对象的世界位置,然后更改其父级,这就是您未获得所需位置的原因。您应该先设置父对象,然后通过 transform.localposition.

设置位置