2013-09-21 36 views
2

目前我正在試圖以我的相機鎖定到地圖我在Unity3D使用此代碼是從JavaScript轉換做:統一:不能修改`值類型返回值UnityEngine.Transform.position」

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

但團結不斷在編譯時返回以下錯誤:error CS1612: Cannot modify a value type return value of 'UnityEngine.Transform.position'. Consider storing the value in a temporary variable.

回答

0

About Compiler Error CS1612

您不應該修改相機位置的方式。

+0

該腳本並不打算修改相機的位置。它的意思攝像機限制爲最大/最小X和Z值 – HMT

+0

在你的代碼說「transform.position.z的新值Mathf.Clamp(transform.position.z,ZMIN,ZMAX)」,但改造。 position.z是原始transform.position座標的副本,因爲它是值類型,並且按值複製。 夾緊位置(和在統一腳本參考也使用)的正確方法: > transform.position =新的Vector3(Mathf.Clamp(transform.position.x,XMIN,XMAX),0,Mathf.Clamp(transform.position .x,xmin,xmax);); –

+0

謝謝,我設法使用上面的腳本將相機夾在地圖上,我不得不修改它一下。但它的作品:D – HMT

0

您不能修改位置的單個座標。你必須重新分配整個向量:

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

因爲Vector3struct,意思是「價值型」,而不是「引用類型」。所以,物業Transform.position的獲得者返回'NEW'Vector3作爲結果。如果直接修改它,則會修改'NEW'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 

這顯然不是你想要的,所以編譯器告訴你這是一個問題。

你應該聲明一個新的Vector3,並初始化爲Transform.position的getter,修改它,並且用它的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,它只是值類型,不會創建內存碎片。