c# - 在访问 MonoBehaviour 的派生类所附加到的 GameObject 时,我应该使用“this”还是“gameObject”?
问题描述
我正在从零开始学习 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
,也可以反过来?
解决方案
它们是不同的东西!
当您使用this
时,您正在引用This关键字,在这种情况下,它指的是MonoBehaviour
您正在编写的。
当您使用 时gameObject
,您正在谈论gameobject
包含您正在编写的行为。这gameObject
可以包含其他MonoBehaviours
.
例如,如果你MonoBehaviour
有一个属性,你可以用“this”来引用它。如果它gameobject
有一个物理组件,您可以使用GetComponent
它来访问它。
推荐阅读
- reactjs - 我想在我的项目的类组件中使用 i18next 但我有这个错误
- docker - arkade:将服务设置为 LoadBalancer
- visual-studio-code - 是否可以对 Visual Studio Code 本身进行实时修改?
- kubernetes - 在所有 pod 上公开随机唯一端口
- node.js - MongoDB $lookup with count ,如果计数为零则返回
- matlab - 如何在 Matlab 中创建随机形状(blob)
- react-native - 如何在菜单问题中修复 React Navigation createMaterialTopTabNavigator 文本上的文本
- python - 我们如何增加 pyqt5 QCombobox 下拉按钮的大小
- java - 春季安全CORS登录
- python - 获取类修饰函数的实例