Copying all the transform values of a gameObject?

Viewed 5379

Is there a way to copy the transform values (position, rotation, scaling) of a gameObject in script. I do not want to copy each transform values separately as given below in the script.

public GameObject Obj02;
public GameObject Obj04;
private Vector3 positionOfObj02;
private Vector3 rotationOfObj02;
private Vector3 positionOfObj04;
private Vector3 rotationOfObj04;

void Start()
{
    positionOfObj02 = Obj02.transform.localPosition;
    rotationOfObj02 = Obj02.transform.localEulerAngles;

    positionOfObj04 = Obj04.transform.localPosition;
    rotationOfObj04 = Obj04.transform.localEulerAngles;
}
2 Answers

No, not built-int but I would recommend a proper type

[Serializable]
public class TransformData
{
    public Vector3 LocalPosition = Vector3.zero;
    public Vector3 LocalEulerRotation = Vector3.zero;
    public Vector3 LocalScale = Vector3.one;

    // Unity requires a default constructor for serialization
    public TransformData() { }

    public TransformData(Transform transform)
    {
        LocalPosition = transform.localPosition;
        LocalEulerRotation = transform.localEulerAngles;
        LocalScale = transform.localScale;
    }

    public void ApplyTo(Transform transform)
    {
        transform.localPosition = LocalPosition;
        transform.localEulerAngles = LocalEulerRotation ;
        transform.localScale = LocalScale;
    }
}

and use it like

public GameObject Obj02;
public GameObject Obj04;

private TransformData transformDataOfObj02;
private TransformData transformDataOfObj04;

void Start()
{
    transformDataOfObj02 = new TransformData(Obj02.transform);
    transformDataOfObj04 = new TransformData(Obj04.transform);
}

and later maybe

transformDataOfObj02.ApplyTo(anotherObject.transform);

I just did this: from.transform.rotation = transform.rotation; This moves the whole rotation

Related