在不实例化的情况下访问 GetComponent()
Accessing GetComponent() without instantiating
我是 Unity 游戏开发的新手,我发现代码中的以下用法有点令人困惑。
private Transform enemy;
// Start is called before the first frame update
void Start()
{
enemy = GetComponent<Transform>();
}
根据文档,GetComponent() 是一个 public 函数。那么如何在不实例化的情况下访问它呢?
我发现在 Unity 的社区上有人提出了类似的问题,但我没有找到任何准确回答问题的答案。请帮助我理解这一点。
link Unity 论坛提问如下。
Question
我的Unity版本是2018.4.16f1
谢谢!
您正在调用添加了 MonoBehavior 的 GameObject 的 GetComponent() 方法,并将其分配给 Transform 敌人。它甚至是您链接问题的第一个答案。
您的 class 很可能继承自 MonoBehaviour
which inherits from Behaviour
which inherits from Component
。
Component
实施 GetComponent
Fazit: 您正在调用此方法的实例正是 this
,实例 Start
被调用。
顺便说一下 Transform
已经有一个专用的 属性 Component.transform
所以你不应该使用 GetComponent
来获得 Transform
参考。
我是 Unity 游戏开发的新手,我发现代码中的以下用法有点令人困惑。
private Transform enemy;
// Start is called before the first frame update
void Start()
{
enemy = GetComponent<Transform>();
}
根据文档,GetComponent() 是一个 public 函数。那么如何在不实例化的情况下访问它呢? 我发现在 Unity 的社区上有人提出了类似的问题,但我没有找到任何准确回答问题的答案。请帮助我理解这一点。 link Unity 论坛提问如下。 Question
我的Unity版本是2018.4.16f1 谢谢!
您正在调用添加了 MonoBehavior 的 GameObject 的 GetComponent() 方法,并将其分配给 Transform 敌人。它甚至是您链接问题的第一个答案。
您的 class 很可能继承自 MonoBehaviour
which inherits from Behaviour
which inherits from Component
。
Component
实施 GetComponent
Fazit: 您正在调用此方法的实例正是 this
,实例 Start
被调用。
顺便说一下 Transform
已经有一个专用的 属性 Component.transform
所以你不应该使用 GetComponent
来获得 Transform
参考。