在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; } }