【问题标题】:Which one should I use "this" or "gameObject" when accessing the GameObject to which the derived class of MonoBehaviour is attached?在访问 MonoBehaviour 的派生类所附加的 GameObject 时,我应该使用“this”还是“gameObject”?
【发布时间】: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,那么问题是:我应该使用哪个来访问组件,因为thisgameObject 都可以调用GetComponent
  • (this.)GetComponent(this.)gameObject.GetComponent 相同。例如(this.)transfrom(this.)gameObject.transform 相同。只是“语法糖”。你只需要指定游戏对象,如果它不是组件所附加的那个(或者你也可以在附加到其他游戏对象的组件上调用它,这意味着 otherGameobject.GetComponent)
  • @yes:我还是不明白你的说法“你只需要指定游戏对象,如果它不是组件所附加的那个(或者你也可以在附加到其他游戏对象的组件上调用它) ,这意味着 otherGameobject.GetComponent)" 。恕我直言,脚本始终附加到游戏对象。如果我通过thisthis.gameObject 调用transformGetComponent,很明显我指的是属于附加脚本的游戏对象的transformGetComponent。所以我还是不明白什么时候必须明确提到gameObject

标签: c# unity3d


【解决方案1】:

它们是不同的东西!

当您使用this 时,您引用的是This 关键字,在这种情况下,它指的是您正在编写的MonoBehaviour

当您使用gameObject 时,您正在谈论包含您正在编写的行为的gameobject。这个gameObject 可以包含其他MonoBehaviours

例如,如果您的MonoBehaviour 有一个属性,您可以用“this”引用它。如果gameobject 有物理组件,您可以使用GetComponent 访问它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-03
    • 2020-02-01
    • 1970-01-01
    • 2013-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多