gameObject 在它所附加的 GameObject 的脚本中是否等同于此?

Is gameObject equivalent to this in the script of the GameObject it is attached to?

我对在编写 Unity 脚本时继承自 MonoBehaviourgameObject 的使用有疑问。

在一些教程中,例如制作缩放的健康条,我们检索健康条的原始比例如下:

originalScale = gameObject.transform.localScale.x;

我稍微研究了一下,发现,因为我正在获取当前正在操作的对象的变换,所以我也可以使用 this:

originalScale = this.transform.localScale.x;

在 Unity 中,这两者是否总是等效的(至少在实施 MonoBehaviour 时)?使用 gameObject 是不是更常见以便清楚我们指的是什么?

this refers to the object described in the script. All Monobehaviour scripts are components, and the this keyword refers to the current component that's executing the code.

gameObject is the game object in the scene. Game objects have components attached to them. From within a Monobehaviour script, you can access the game object that the script is attached to by using either this.gameObject or gameObject which are equivalent.

Reference,因为有人说比我好。


关于transform,这也是一个Component。由于 GameObject 只是组件的容器,因此当您执行 gameObject.transform 时,您指的是该变换组件。

因为任何 GameObject 只有一个变换,this.transform 也会恰好指向相同的组件。

这是一个特例,因为 MonoBehaviour 实际上继承自 Component,如果您查看 Component class

// Summary:
//     ///
//     The Transform attached to this GameObject (null if there is none attached).
//     ///
public Transform transform { get; }

这就是为什么您在两种情况下得到相同结果的原因。