Unity:无法修改`UnityEngine.Transform.position’的值类型返回值

我目前正在尝试使用从JavaScript转换的代码将我的相机锁定到我在Unity3D中制作的地图:

transform.position.z = Mathf.Clamp(transform.position.z, zmin, zmax); transform.position.x = Mathf.Clamp(transform.position.x, xmin, xmax); 

但Unity在编译时继续返回以下错误: error CS1612: Cannot modify a value type return value of 'UnityEngine.Transform.position'. Consider storing the value in a temporary variable. error CS1612: Cannot modify a value type return value of 'UnityEngine.Transform.position'. Consider storing the value in a temporary variable.

关于编译器错误CS1612

你不应该这样修改相机位置。

因为Vector3是一个struct ,意味着’值类型’,而不是’引用类型’。 所以,属性Transform.position的getter为结果返回一个’ Vector3 。 如果你直接修改它,’ Vector3被修改,’NOT’是Transform.position属性。 明白了吗?

 Transform.position.x = 0; // this is wrong code // is same with Vector3 _tmp = Transform.position; // getter _tmp.x = 0; // change 'NEW' Vector3 

这显然不是你想要的,所以编译器告诉你这是一个问题。

你应该使用Transform.position的getter声明一个新的Vector3和init,修改它,并用它的setter改变Transform.position

 Vector3 _tmp = Transform.position; // getter _tmp.x = 0; // change 'NEW' Vector3 Transform.position = _tmp; // change Transform.position with it's setter 

不要担心Vector3 _tmp ,它只是值类型,不会创建内存碎片。

您无法修改位置的单个坐标。 你必须重新分配整个向量:

 Vector3 newVal; newVal.x = transform.position.x = Mathf.Clamp(transform.position.x, xmin, xmax); ... transform.position = newVal;