GameObject 使用position的set方法改变位置无效

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

 

posted @ 2014-01-17 21:09  michael111  阅读(5588)  评论(0编辑  收藏  举报