[Unity]不用GetComponent<Transform>()得到的transform
Copyright Notice: This article is an original work licensed under the CC 4.0 BY-NC-ND license.
If you wish to repost this article, please include the original source link and this copyright notice.
Source link: https://v2know.com/article/225
在《Unity5权威讲解》这本书中,
第一份代码就要求你在Void Start()方法中声明
tr=GetComponent<Transform>()
所以你每次都会在类中先private Transform tr;
然后通过获取组件的方式,来给tr赋值。
其实有一个等价的方案:
void Start()
{
//tr = GetComponent<Transform>();
tr = transform;
}
这样实现的效果是一样的。
transform是Unity对象的固有属性之一,
目前看来,Unity似乎直接帮你定义好了这个静态变量,你可以直接使用。
另外有一个新的,更简单的解决方案:
[1] Unity通过Attribute代替getComponent获取组件
This article was last edited at 2020-04-03 03:18:11