【问题标题】:The 'this' keyword in Unity3D scripts (c# script, JavaScript)Unity3D 脚本(c# 脚本、JavaScript)中的“this”关键字
【发布时间】:2013-07-23 14:05:15
【问题描述】:

我很困惑:

代码(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:Unity 中的脚本包括附加自定义脚本 对象称为游戏对象的行为。

2> 在Component 对象中,transform、renderer、rigidbody 等变量被引用到gameObject 这个Component 所附加的组件。所以在脚本中,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 指的是脚本对象,而不是脚本附加的游戏对象,对吧?

【问题讨论】:

    标签: unity3d


    【解决方案1】:

    如果您将CS01 附加到场景中的一个游戏对象并且该游戏对象将被加载,您将拥有每个对象的一个​​实例。在CS01 的构造过程中,在调用AwakeOnEnable 之前,会初始化gameObjecttranformname 等所有属性。如果它们引用一个对象,它们中的大多数将获得对父属性的引用。

    string 类在 C# 或 java 中有些特殊,其行为类似于 struct - 它会被复制。详细说明:CS01.name(继承自Unity.Object)将获取游戏对象的名称。只要它们具有相同的名称,两个变量都指向内存中的相同位置。当您更改 CS01 的名称时,将在内部创建一个新的 string 实例,并使用您分配给它的文本进行初始化。因此,游戏对象的原始 i.e.name 属性将保持不变。

    1. 是的
    2. 大多数组件都有引用GameObject 属性的属性,一种快捷方式
    3. 与 2 中一样。name 在基类 Object 中定义。 GameObjectMonoBehaviour 都派生自 Unity.Object
    4. 没错,这就是你在代码中编写的类

    【讨论】:

    • 但是根据我的理解,脚本中thisCS01的一个瞬间,它源自MonoBehaviour,所以,如果我改了name,它不会影响@ 987654343@它附在上面。 CubeCS01之间的关系应该是组合的。
    • name 是 MonoBehavior 的一个属性,它实际设置/获取 GameObject 名称。凯所说的捷径。所以实际上 this.name 和 gameObject.name 指向同一个值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-03
    • 2017-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多