Home > Net >  Unity3D - transform.position doesn't work
Unity3D - transform.position doesn't work

Time:04-06

I made this script attached to the shotgun on scene so it would move it in the hierarchy to be a child of player and reset to position to 0,0,0 but the position is random every time. If I run the script to reset position without changing the parent the position will change to 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

CodePudding user response:

You note that even the Inspector tells you: What you see in the Inspector is always the local Transform.localPosition relative to the local space of the parent, not the global / absolute world space Transform.position!

Only in the case that there is no parent the position and localPosition are the same.

=> you want to rather use

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

in order to place the object to the pivot of the parent (or world if there is none).

  • Related