在Unity中比較多的一個操作是改變GameObject的位置,那么存在的一種改變方法如下:
GameObject go = new GameObject(); go.transform.position.set(1.0f, 1.0f, 1.0f); // 設置go的位置為(1.0f, 1.0f, 1.0f)
可是上面兩句代碼執行后對GameObject的位置完全沒有起到改變的作用,從下面的網站或許可以找到一點端倪
http://answers.unity3d.com/questions/225729/gameobject-positionset-not-working.html
其中一個回答:
As far as I can tell, this happens because when you use 'transform.position', it returns a new vector3, rather than giving you a reference to the actual position. Then, when you use Vector3.Set(), it modifies the returned Vector3, without actually changing the original! This is why you have to be careful about exactly how the values are passed around internally. Transform.position and Rigidbody.velocity are not simply direct references to the values that they represent- there is at least one layer of indirection that we can't exactly see from the outside.
簡而言之:使用transform.position的時候,Unity內部返回了一個新的vector3對象,所以使用set方法修改的只是返回的新vector3對象的值,並沒有修改transform.position實際的值,這也就出現了上述一段代碼執行后並沒有改變GameObject位置的現象。
那么為了達到目的,我們正確的一種寫法:
GameObject go = new GameObject(); go.transform.position = new Vector3(1.0f, 1.0f, 1.0f);
猜測transform.position內部的實現:
private Vector3 _position; public Vector3 position { get { return new Vector3(_position.x, _position.y, _position.z); } set { _position = value; } }