复制游戏对象的所有变换值?

时间:2019-06-27 15:10:46

标签: c# unity3d

有没有一种方法可以在脚本中复制游戏对象的变换值(位置,旋转,缩放)。我不想单独复制每个转换值,如下面在脚本中给出的。

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 个答案:

答案 0 :(得分:3)

不,不是内建的,但我建议使用正确的类型

[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;
    }
}

并像

一样使用它
public GameObject Obj02;
public GameObject Obj04;

private TransformData transformDataOfObj02;
private TransformData transformDataOfObj04;

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

以后也许

transformDataOfObj02.ApplyTo(anotherObject.transform);

答案 1 :(得分:0)

我只是这样做:from.transform.rotation = transform.rotation; 这会移动整个旋转