Add new comment

Placing stuff in 3D space in Unity 3D is simple, right? Just use this.transform.position and you are all set – or so we have been taught in art school. Turns out there are a few pitfalls I happen to hit whenever I work with that stuff.

Reading and Writing Values of transform.position

Yes, you can access the x, y, and z-values of the transform.position. But you can not change them directly (at least in C#). You have to use a Vector3 object, as in:

this.transform.position = new Vector3(newX, newY, newZ);

Obviously, by feeding the original values in, you can change just one value at a time:

this.transform.position = new Vector3(this.transform.position.x, newY, this.transform.position.y);

Global vs. Local

Also of note: transform.position actually refers to the position in global space, it is the absolute position.

In many cases, you want to calculate movement relative to the parent object. In order to do this, you need to use transform.localPosition, which works exactly as the other one, but is calculated relatively to the position of the parent object. If there is no parent object, localPosition is the same as position.

In my opinion, it is in many cases better to use localPosition instead of position, since most of the time, you want to have objects move with or along their parent objects. After all, also the editor shows you the local position.