Let's look at accessing a variable in LearningScript
from inside LearningScript
.
Here are the outputs in the Console:
An analysis of the code shown in the previous code screenshot is as follows:
Line 6: string myString = "Access the variable ";
Line 17: Debug.Log(myString + "the normal way.");
string
value in myString
, Accessing this variable
, is substituted for the variable namemyString
is being accessed without using Dot Syntax or GetComponent()
, because a script always has access to its own variables and methodsLine 18: Debug.Log(this.myString + "using 'this' keyword.");
myString
is being accessed using Dot Syntaxthis
keyword refers to the current instance of the class, the current ComponentLine 19: Debug.Log(GetComponent<LearningScript>().myString + "using GetComponent.");
myString
is being accessed using Dot Syntax againGetComponent<T>()
method is retrieving the LearningScript
ComponentLine 22: Debug.Log(this);
this
, the Component is sent to the Console so we can see that this
is the current LearningScript
Component objectLine 23: Debug.Log(GetComponent<LearningScript>());
GetComponent<LearningScript>()
, the Component is sent to the Console, so we can see this also is the current LearningScript
Component objectthis
keyword and GetComponent<LearningScript>()
are both retrieving the same LearningScript
Component objectWhoa!! What's with line 18?
Notice item 1 in the graphic under the section, Accessing a Component's own variables and methods? This is the usual way we will access variables and methods in the current script; no Dot Syntax required. This is how we've been doing it from the beginning of this book. It's how we will probably continue to access them. However, we do have the option of accessing the variables and methods in the current Component object using Dot Syntax.
As you can see from the output of lines 17 and 18, the value stored in myString
is substituted no matter how we access myString
.
So if we really wanted to, we could use the GetComponent()
method to retrieve the current Component object of the LearningScript
class in memory, then use Dot Syntax to access myString
. However, C# provides a shortcut to get the current Component object by using the this
keyword.
Item 2 in the graphic is the syntax used in line 18. In this example, the keyword this
simply means the current instance object of the LearningScript
class, the current Component.
Now we start to just touch on the real power of Dot Syntax, communicating with other objects to access variable data and methods. We will now communicate with another Component on the same GameObject, the Main Camera. Remember, LearningScript
is attached to the Main Camera already. The following diagram will explain how this is done:
3.137.223.10