unity-game-engine - Unity3D 脚本中的 'this' 关键字(c# 脚本、JavaScript)

标签 unity-game-engine

我很困惑:

代码(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 附加到场景中的一个游戏对象,并且该游戏对象将被加载,那么您将拥有每个游戏对象的一个​​实例。在调用 AwakeOnEnable 之前构建 CS01 期间,所有属性如 gameObjecttranformname 等已初始化。如果它们引用一个对象,它们中的大多数将获得对父级属性的引用。

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

  1. 大多数组件都具有引用 GameObject 属性的属性,这是一种快捷方式
  2. 如 2 所示。name 在基类 Object 中定义。 GameObjectMonoBehaviour 均派生自 Unity.Object
  3. 确切地说,这就是您在代码中编写它的类

关于unity-game-engine - Unity3D 脚本中的 'this' 关键字(c# 脚本、JavaScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17828217/

相关文章:

unity-game-engine - 是否有用于在运行时创建图像目标的 AR SDK?

unity-game-engine - 如何获得 Sprite 的平均颜色? (Unity3d)

ios - 在 Xcode 上构建并在 Testflight 上测试后,应用程序启动时出现粉红色屏幕和空白屏幕

unity-game-engine - 在 Unity 增强现实中显示屏幕 UI 按钮

c# - 获取 Unity 中的预制件文件位置

c# - 如何避免每一帧的类型检查?

c# - AssetDatabase.Refresh 准备就绪时发出通知

javascript - 如何在Unity(5.6.0)中访问文本字段的值?

android - E/FirebaseInstanceId : Error while delivering the message: ServiceIntent not found

java - 通过 Unity/Java 插件启动 Android 应用程序