【发布时间】:2019-06-18 01:29:22
【问题描述】:
我正在从零开始学习 Unity3D。我发现我们可以访问GameObject,它附加了一个声明MonoBehaviour派生类的脚本,如下所示。
- 通过
this - 通过
gameObject - 通过具有
[SerializedField]属性的私有字段。
简单代码
using UnityEngine;
public class Ball : MonoBehaviour
{
[SerializeField]
private GameObject ball;
void Update()
{
Vector3 force = new Vector3
{
x = 5 * Input.GetAxis("Horizontal"),
y = 0,
z = 5 * Input.GetAxis("Vertical")
};
//gameObject.GetComponent<Rigidbody>().AddForce(force);
//this.GetComponent<Rigidbody>().AddForce(force);
ball.GetComponent<Rigidbody>().AddForce(force);
}
}
问题
在这三个中,我只想知道我们什么时候需要选择this而不是gameObject,反之亦然?
【问题讨论】:
-
您不应该在 Update 中调用 GetComponent。这对性能非常不利。你应该缓存刚体。
-
this指的是“这个类”的实例(你写这个的那个),gameObject你指的是你的 MonoBehaviour(又名组件)附加到的游戏对象。[SerializedField]允许您向检查员公开一个私有字段(统一编辑器 gui)。这三件事根本不同 -
@yes,那么问题是:我应该使用哪个来访问组件,因为
this和gameObject都可以调用GetComponent? -
(this.)GetComponent与(this.)gameObject.GetComponent相同。例如(this.)transfrom与(this.)gameObject.transform相同。只是“语法糖”。你只需要指定游戏对象,如果它不是组件所附加的那个(或者你也可以在附加到其他游戏对象的组件上调用它,这意味着 otherGameobject.GetComponent) -
@yes:我还是不明白你的说法“你只需要指定游戏对象,如果它不是组件所附加的那个(或者你也可以在附加到其他游戏对象的组件上调用它) ,这意味着 otherGameobject.GetComponent)" 。恕我直言,脚本始终附加到游戏对象。如果我通过
this或this.gameObject调用transform或GetComponent,很明显我指的是属于附加脚本的游戏对象的transform或GetComponent。所以我还是不明白什么时候必须明确提到gameObject?