this in unity
The “this” keyword in C# is used to refer to the current instance of the class. It is also used to differentiate between the method parameters and class fields if they both have the same name Example code: using System; namespace ThisKeyword { class Test { int num; Test(int num) { // this.num refers to the instance field this.num = num; } static void Main(string[] args) { Test t1 = new Test(4); Console.WriteLine("value of num: " +t1.num); Console.ReadLine(); } } } // output: value of num: 4
Here is what the above code is Doing:
1. The Test class has a field called num and a constructor that takes an int as a parameter.
2. The constructor assigns the value of the parameter to the field.
3. The Main method creates an instance of the Test class and passes the value 4 to the constructor.
4. The constructor assigns the value of the parameter to the field.
5. The Main method prints the value of the field.