问题
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.
- Yes
- Most components have properties that refer to the
GameObject
properties, kind of shortcut - Like in 2.
name
is defined in base classObject
.GameObject
andMonoBehaviour
both are derived fromUnity.Object
. - 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