Reputation: 43
I am currently trying to lock my camera to a map I made in Unity3D using this code that was converted from JavaScript:
transform.position.z = Mathf.Clamp(transform.position.z, zmin, zmax);
transform.position.x = Mathf.Clamp(transform.position.x, xmin, xmax);
But Unity keeps on returning the following error while compiling: error CS1612: Cannot modify a value type return value of 'UnityEngine.Transform.position'. Consider storing the value in a temporary variable.
Upvotes: 3
Views: 13249
Reputation: 1103
because Vector3
is a struct
, means 'value type', not 'reference type'. so, the property Transform.position
's getter return a 'NEW' Vector3
for result. if you modify it directly, the 'NEW' Vector3
is modified, 'NOT' the Transform.position
property. is that clear?
Transform.position.x = 0; // this is wrong code
// is same with
Vector3 _tmp = Transform.position; // getter
_tmp.x = 0; // change 'NEW' Vector3
this is obviously NOT what you want, so compiler told you that's a problem.
you should declare a new Vector3
, and init with Transform.position
's getter, modify it, and change Transform.position
with it's setter.
Vector3 _tmp = Transform.position; // getter
_tmp.x = 0; // change 'NEW' Vector3
Transform.position = _tmp; // change Transform.position with it's setter
don't worry about Vector3 _tmp
, it's just value type, won't create memory fragmentations.
Upvotes: 11
Reputation: 39194
You can't modify the single coordinate of the position. You have to reassign the whole vector:
Vector3 newVal;
newVal.x = transform.position.x = Mathf.Clamp(transform.position.x, xmin, xmax);
...
transform.position = newVal;
Upvotes: 1