Time for action – accessing a variable in the current Component
Let's look at accessing a variable in LearningScript
from inside LearningScript
.
Modify
LearningScript
as shown in the following figure:Save the file.
In Unity, click on Play.
What just happened?
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 ";
myString
is the variable that will be accessedNotice that it's
private
by default, yet it can still be accessed
Line 17: Debug.Log(myString + "the normal way.");
This is how we have been accessing the value stored in a variable, by just using the variable name
The
string
value inmyString
,Accessing this variable
, is substituted for the variable namemyString
is being accessed without using Dot Syntax orGetComponent()
, because a script always has access to its own variables and methods
Line 18: Debug.Log(this.myString + "using 'this' keyword.");
myString
is being accessed using...