在Unity中比較多的一個操做是改變GameObject的位置,那麼存在的一種改變方法以下:html
GameObject go = new GameObject(); go.transform.position.set(1.0f, 1.0f, 1.0f); // 設置go的位置爲(1.0f, 1.0f, 1.0f)
但是上面兩句代碼執行後對GameObject的位置徹底沒有起到改變的做用,從下面的網站或許能夠找到一點端倪web
http://answers.unity3d.com/questions/225729/gameobject-positionset-not-working.htmlapp
其中一個回答:ide
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位置的現象。this
那麼爲了達到目的,咱們正確的一種寫法:spa
GameObject go = new GameObject(); go.transform.position = new Vector3(1.0f, 1.0f, 1.0f);
猜想transform.position內部的實現:3d
private Vector3 _position; public Vector3 position { get { return new Vector3(_position.x, _position.y, _position.z); } set { _position = value; } }