📅  最后修改于: 2023-12-03 15:05:35.278000             🧑  作者: Mango
As a programmer, you might have heard of the keyword "this" in C#, but do you know how it is used in Unity? In this article, we will dive into the usage of "this" in Unity and how it can help you write better scripts.
this
in C#?In C#, this
is a keyword that refers to the current instance of the class. It is often used to qualify members of the class, differentiate between class members and local variables, or pass the current instance of a class as a parameter to methods.
public class MyClass {
private int myValue;
public MyClass(int value) {
this.myValue = value;
}
}
In the example above, this.myValue
refers to the private field myValue
of the current instance of MyClass
.
In Unity, the usage of this
is similar to C#, but it can also have some specific meanings and conventions that are related to the Unity engine. Here are some examples:
You can use this
to reference components attached to the game object the script is attached to.
public class MyBehaviour : MonoBehaviour {
private Rigidbody myRigidbody;
private void Start() {
this.myRigidbody = this.GetComponent<Rigidbody>();
}
}
In the example above, this
is used to refer to the current instance of MyBehaviour
. By calling this.GetComponent<Rigidbody>()
, we can retrieve the Rigidbody
component attached to the same game object as the script.
By using this
, you can access variables defined in the same class, even if their names clash with local variables.
public class MyBehaviour : MonoBehaviour {
private int myValue;
private void Update() {
int myValue = 5;
Debug.Log("Local value: " + myValue);
Debug.Log("Class value: " + this.myValue);
}
}
In the example above, we have both a local variable myValue
and a class variable with the same name. By using this.myValue
, we can access the class variable and differentiate it from the local variable.
this
can also be used to call methods and properties of the current instance.
public class MyBehaviour : MonoBehaviour {
public float myValue { get; private set; }
public void SetMyValue(float value) {
this.myValue = value;
}
}
In the example above, this.myValue
refers to the property myValue
of the current instance of the class. By using this.SetMyValue(10f)
, we can call the method SetMyValue
of the instance and set its myValue
property to 10.
In this article, we have explored the usage of this
in Unity and how it can help you write better scripts. By using this
, you can reference components, access class variables or methods, and differentiate them from local variables. Keep in mind that this
is just a keyword, and it is up to you to use it wisely and efficiently in your code.