0

I'm writing a script for locking scale of objects in Unity.

Since objectTransformScale = objectTransform.localScale.

Changes made on objectTransformScale should also affect objectTransform.localScale, but it doesn't.

Hence I have to set the value back as objectTransform.localScale = objectTransformScale;

Why doesn't it work?

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;
}
Y.Wang
  • 149
  • 1
  • 10
  • 2
    Possible duplicate of [What is the difference between a reference type and value type in c#?](https://stackoverflow.com/questions/5057267/what-is-the-difference-between-a-reference-type-and-value-type-in-c) ... Hint: [`Vector3`](https://docs.unity3d.com/ScriptReference/Vector3.html) is a `struct` and therefor a value type, `Transform` is a `class` and therefor a reference type ;) – derHugo Feb 18 '19 at 15:00
  • probably not here @derHugo. Classes in Unity are default reference I think always. – Prodigle Feb 18 '19 at 15:01
  • 3
    @Prodigle [`Vector3`](https://docs.unity3d.com/ScriptReference/Vector3.html) is a `struct` not a `class` – derHugo Feb 18 '19 at 15:02
  • Ah right! Thatt'l be it then – Prodigle Feb 18 '19 at 15:03

1 Answers1

0
objectTransformScale = Vector3(ref objectTransform.localScale);

Structs are value types so they just pass the data without including a reference to themselves. You were essentially making a copy of local scale and editing the copy. Using ref in a constructor makes sure the two are linked.

Prodigle
  • 1,757
  • 12
  • 23
  • 1
    This is not valid `c#`: `error CS0119: Expression denotes a 'type', where a 'variable', 'value' or 'method group' was expected`. There is no constructor for `Vector3` taking a `ref` as parameter (and if there was one you would have to use `new`). You can't just convert a value type into a reference type – derHugo Feb 18 '19 at 15:08