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

 

转载于:https://www.cnblogs.com/sutingwei/p/3524567.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值