4

我很困惑:

代码 (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> 在Componentobject 中,transform、renderer、rigidbody 等变量都引用到gameObjectthisComponent附加到的组件。所以在脚本中,this.renderer.material.color = Color.red;等价于this.gameObject.renderer.material.color = Color.red. name但是,文档中对变量的描述name: The name of the object.只告诉它是对象的名称。
3> 那么,如何理解上面的代码呢?该变量是否name还返回name此脚本附加到的游戏对象的?
4>this指的是脚本对象,而不是脚本附加的游戏对象,对吧?

4

1 回答 1

3

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

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

  1. 是的
  2. 大多数组件都有引用属性的GameObject属性,一种快捷方式
  3. 就像在 2.name中定义的基类一样ObjectGameObject两者MonoBehaviour都来自Unity.Object.
  4. 确切地说,这是您在代码中编写它的类
于 2013-07-24T08:08:57.583 回答