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.
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.
About Compiler Error CS1612
You shouldn't modify camera position that way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With