为什么当我更改参考A的值时,原始实例没有变化?

时间:2019-02-18 14:58:54

标签: c# unity3d

我正在编写一个脚本来锁定Unity中的对象比例。

objectTransformScale = objectTransform.localScale起。

objectTransformScale上所做的更改也应影响objectTransform.localScale,但不会。

因此,我必须将值重新设置为objectTransform.localScale = objectTransformScale;

为什么不起作用?

public string demension; 

private Transform objectTransform;
private Vector3 objectTransformScale;
private float originalX;
private float originalY;
private float originalZ;

// Use this for initialization
void Start () {
    objectTransform = GetComponent<Transform>();
    objectTransformScale = objectTransform.localScale;
    originalX = objectTransformScale.x;
    originalY = objectTransformScale.y;
    originalZ = objectTransformScale.z;
}

// Update is called once per frame
void Update () {
    objectTransformScale = objectTransform.localScale;
    if (demension.Equals("x"))
    {
        objectTransformScale.x = originalX;
    }
    else if(demension.Equals("y"))
    {
        objectTransformScale.y = originalY;
    }
    else if(demension.Equals("z"))
    {
        objectTransformScale.z = originalZ;
    }
    else if (demension.Equals("a"))
    {
        objectTransformScale.z = originalZ;
        objectTransformScale.y = originalY;
        objectTransformScale.x = originalX;
    }
    //The scale of object won't be locked if I command the line below.
    objectTransform.localScale = objectTransformScale;
}

1 个答案:

答案 0 :(得分:0)

Network Service

结构是值类型,因此它们仅传递数据而不包含对自身的引用。您实质上是在复制本地比例并编辑该副本。在构造函数中使用ref可以确保两者链接。