Hello,
when I do
transform.localScale = new Vector3(2,1,1);
my object scales properly,
however when I do:
transform.localScale.Set(2,1,1);
its scale doesn’t change. Why?
thanks in advance,
Dawid
Hello,
when I do
transform.localScale = new Vector3(2,1,1);
my object scales properly,
however when I do:
transform.localScale.Set(2,1,1);
its scale doesn’t change. Why?
thanks in advance,
Dawid
The Set method is a method of the Vector3 struct to set it’s 3 components at once. However it doesn’t work in this case because:
Properties of struct types have an inconvinient problem: When you access a member of such a struct you actually access the get method of the property. Since the get method will return a copy of the struct (since values types are always copied when you assign / return them) any changes you do to that copy has no effect. To actually change the scale you have to invoke the set method of the property. The set method is invoked whenever you assign a Vector3 to the localScale property.
This would work:
Vector3 tmp = transform.localScale;
tmp.Set(2, 1, 1);
transform.localScale = tmp;
but it wouldn’t make much sense. It makes more sense to directly assign the desired Vector3
transform.localScale = new Vector3(2,1,1);
Note that the same holds true for localPosition, localRotation, position, rotation, … Basically every property of a struct type.
That’s why those two examples do not work:
Transform t;
Material m;
t.position.x = 4;
m.color.r = 0.5f;
In those cases you have to use a temp variable:
Vector3 tmpPos = t.position; // getter
tmpPos.x = 4;
t.position = tmpPos; // setter
Color tmpCol = m.color; // getter
tmpCol.r = 0.5f;
m.color = tmpCol;
This is the only way to change just a single member of such a struct and keep the others.
So basically this problem is for all members that are structs and properties at the same time. When I modify particular fields I modify struct copy and to avoid this I need to set whole structure to new value.
Another solution would be to never use structs that are properties, just regular members (but in this case I obviousely cannot modify Unity sources).
Thank You