The 'this' keyword in Unity3D scripts (c# script, JavaScript)

给你一囗甜甜゛ 提交于 2021-02-07 08:20:35

问题


I'm confused that:

CODE (CS01.cs)

The script is attached to a simple Cube object.

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> Will CS01 be an script object right?

DOC: Scripting inside Unity consists of attaching custom script objects called behaviours to game objects.

2> In Component object, variables like transform, renderer, rigidbody are referenced to the components of gameObject this Component attached to. So in the script, this.renderer.material.color = Color.red; is equivalent to this.gameObject.renderer.material.color = Color.red. However, the description of variable name in the document name: The name of the object. only tells it's the name of the object.
3> So, how to understand the code above? Does the variable name also return the name of the gameObject this script attached to?
4> this means the script object but not the gameObject the script attached to, right?


回答1:


If you attach CS01 to a game object in the scene and this game object will be loaded, you will have one instance of each. During the construction of CS01 before Awake and OnEnable are called, all properties like gameObject, tranform, name, etc. are initialised. Most of them will get a reference to the parent's properties if they are refering to an object.

string class is somewhat special in C# or java and behaves rather like a struct - it will be kind of copied. In detail: CS01.name (which is inherited from Unity.Object) will get the game object's name. As long as they have both the same name, both variables point to the same place in memory. When you change CS01's name, a new string instance will be created internally and be initialised with the text you assign to it. Thus the original i.e. name property of game object will remain unchanged.

  1. Yes
  2. Most components have properties that refer to the GameObject properties, kind of shortcut
  3. Like in 2. name is defined in base class Object. GameObject and MonoBehaviour both are derived from Unity.Object.
  4. Exactly, this is the class where you writing it in the code


来源:https://stackoverflow.com/questions/17828217/the-this-keyword-in-unity3d-scripts-c-script-javascript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!