我很困惑:
代码(CS01.cs)
该脚本附加到一个简单的 Cube 对象。
using UnityEngine;
using System.Collections;
public class CS01 : MonoBehaviour {
// Use this for initialization
void Start () {
Debug.Log (this); //--> Cube(CS01)
Debug.Log (this.GetType()); //--> CS01
Debug.Log (this.GetType() == typeof(UnityEngine.GameObject)); //--> False
Debug.Log (this == gameObject); //--> False
Debug.Log (this.name); //--> Cube
Debug.Log (gameObject.name); //--> Cube
this.name = "Hello"; // --> Will get the gameObject's name changed to 'Hello'
Debug.Log (gameObject.name); //--> Hello
}
// Update is called once per frame
void Update () {
}
}
1> CS01
是一个脚本对象吗?
DOC: Scripting inside Unity consists of attaching custom script objects called behaviours to game objects.
2> 在 Component
对象中,变换、渲染器、刚体等变量引用到此 Component
附加的 gameObject
组件。因此在脚本中,this.renderer.material.color = Color.red;
相当于this.gameObject.renderer.material.color = Color.red
。然而,文档name: The name of the object.
中对变量name
的描述仅告诉它是对象的名称。
3> 那么,如何理解上面的代码呢?变量 name
是否也返回此脚本所附加的游戏对象的 name
?
4> this
表示脚本对象,而不是脚本附加的游戏对象,对吗?
最佳答案
如果将 CS01
附加到场景中的一个游戏对象,并且该游戏对象将被加载,那么您将拥有每个游戏对象的一个实例。在调用 Awake
和 OnEnable
之前构建 CS01
期间,所有属性如 gameObject
、tranform
、name
等已初始化。如果它们引用一个对象,它们中的大多数将获得对父级属性的引用。
string
类在 C# 或 java 中有些特殊,其行为类似于 struct
- 它将是某种复制。具体来说:CS01.name
(继承自Unity.Object
)将获取游戏对象的名称。只要它们具有相同的名称,两个变量就指向内存中的同一位置。当您更改 CS01 的名称时,将在内部创建一个新的 string
实例,并使用您分配给它的文本进行初始化。这样游戏对象的原始属性即 name 属性将保持不变。
- 是
- 大多数组件都具有引用
GameObject
属性的属性,这是一种快捷方式 - 如 2 所示。
name
在基类Object
中定义。GameObject
和MonoBehaviour
均派生自Unity.Object
。 - 确切地说,这就是您在代码中编写它的类
关于unity-game-engine - Unity3D 脚本中的 'this' 关键字(c# 脚本、JavaScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17828217/