0
\$\begingroup\$

Unity has both transform.positionandtransform.localPosition. When I do transform.position.x += 3f; does unity automatically update transform.localposition? and vice versa?

Why can I not see this when I go to the definition of transform.position in VS?

\$\endgroup\$
1
  • \$\begingroup\$ What do your experiments tell you when you change position then read localPosition or vice versa? \$\endgroup\$ – DMGregory Jun 5 '20 at 18:41
1
\$\begingroup\$

When you set transform.position in Unity, the engine automatically calculates the corresponding local position the object needs relative to its parent to arrive at that location, and sets its local position there.

When you set transform.localPosition, the local position is updated directly. Subsequent attempts to read transform.position or use any of the Transform's transformation methods will use this new local position - in addition to any parent transforms.

(Don't underestimate your power to find these things out through your own testing - a short script that sets position or localPosition and prints the values of both before and after would have answered most of your question, much faster than waiting for a stranger to reply here!)

In C# code, this would look something like this:

public Vector3 position {
    get {
        if (parent == null)
            return localPosition;

        return parent.TransformPoint(localPosition);
    }

    set {
        if (parent == null)
             localPosition = value;
        else
             localPosition = parent.InverseTransformPoint(value);
        hasChanged = true;
    }
}

The reason you don't see this implementation in Visual Studio is likely because this isn't implemented in managed C# code, but in the engine's underlying C++ code, compiled down to a native binary, to which the C# representation just provides a wrapper.

\$\endgroup\$
1
  • \$\begingroup\$ You're right I thought about doing my own testing and I could have seen the updates to transform but it would still leave me wonder why I can't see this and why this is so obscure. I searched google and I found nothing on this. It's not clear when I go to the definition either, there's only a property declaration but no definition \$\endgroup\$ – xcrypt Jun 5 '20 at 22:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.