Unity3D - transform.position 不起作用

Unity3D - transform.position doesn't work

我将此脚本附加到场景中的霰弹枪,因此它会在层次结构中将其移动为玩家的子级并重置为 0,0,0 的位置,但位置每次都是随机的。如果我 运行 在不更改父级的情况下重置位置的脚本,位置将更改为 0,0,0:

public void Update()
{
        if (Input.GetKeyDown(KeyCode.E))
        {
            transform.position = new Vector3(0.0f, 0.0f, 0.0f);
            transform.SetParent(weaponPosition);
            transform.position = new Vector3(0.0f, 0.0f, 0.0f);
        }
}

On start before pressing E

after pressing E

您注意到,即使 Inspector 也会告诉您:您在 Inspector 中看到的始终是 local Transform.localPosition relative to the local space of the parent, not the global / absolute world space Transform.position!

只有在没有parent的情况下,positionlocalPosition才相同

=> 您想使用

transform.SetParent(weaponPosition);
transform.loalPosition = Vector3.zero;

为了将 object 放置到 parent 的枢轴(或世界,如果有 none)。