0
\$\begingroup\$

As the title suggests, I am looking to serialize on the Inspector a Vector3 that behaves just as the Transform's position Vector3:

  • If you modify the position Vector3, the GameObject positions itself according to the World Position.
  • If you move the GameObject on the scene by picking the handles, the GameObject moves, and the position Vector3 gets modified equal to the GameObject's position.

So, is there a way I can constrain a serialized Vector3, so if I modify it on the inspector I can change the GameObject's position, like this:

[ExecuteInEditMode]
public class LameExample : MonoBehaviour
{
    public Vector3 transformPosition;

    private void Update()
    {
        if(modifyingVectorOnInspector)
        transform.position = transformPosition;
        else if(gameObjectIsBeingMovedOnScene)
        transformPosition = transform.position;
    }
}

I've tried an approach using Selection.contains(gameObject), but that does not take into account if it is dragged by the handles.

Thanks in advance for your help.

\$\endgroup\$
  • \$\begingroup\$ I'd go with a custom inspector script for this, myself. \$\endgroup\$ – Draco18s Mar 2 '18 at 0:19
1
\$\begingroup\$

This seems to work, using the Reset method to initialize the position when the component is added, and OnValidate to react to changes made in the inspector.

[ExecuteInEditMode]
public class PositionMatch : MonoBehaviour {

    public Vector3 position;

#if UNITY_EDITOR
    void Reset() {
        position = transform.position;
    }

    void OnValidate() {
        if(transform.position != position) {
            UnityEditor.Undo.RecordObject(transform, "change position via variable.");
            transform.position = position;
        }
    }   

    void Update () {
        if(transform.position != position) {
            UnityEditor.Undo.RecordObject(this, "change position via Transform.");
            position = transform.position;
        }
    }
#endif
}

Note that Unity's == operator for Vector3s has a little tolerance. If you don't want that, check them componentwise or validate that their difference has zero squared magnitude.

\$\endgroup\$
  • \$\begingroup\$ Works as expected! Thank you very much. Sorry for the late vote. \$\endgroup\$ – LifGwaethrakindo Mar 2 '18 at 19:11

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.