首页 > 解决方案 > 在访问 MonoBehaviour 的派生类所附加到的 GameObject 时,我应该使用“this”还是“gameObject”?

问题描述

我正在从零开始学习 Unity3D。我发现我们可以访问GameObject一个声明派生类的脚本MonoBehaviour,如下所示。

琐碎的代码

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,也可以反过来?

标签: c#unity3d

解决方案


它们是不同的东西!

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

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

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


推荐阅读