Let's create another script with a variable and a method, and attach it to the Main Camera, then have LearningScript
communicate with it:
TalkToMe
.public
string
variable named hereItIs
.hereItIs
.public
method named MakeMeTalk()
.MakeMeTalk()
output some text to the Console.MakeMeTalk()
to the Main Camera. Now the code should look something like this:LearningScript
to retrieve the TalkToMe
Component.LearningScript
to retrieve the data in hereItIs.
LearningScript
to call the MakeMeTalk()
method. Now the code snippet should look as follows:The LearningScript
Component code retrieved a variable and called a method on the TalkToMe
Component. Let's follow the code flow with these two Components.
An analysis of the code shown in the previous code screenshot is as follows:
On LearningScript:
Line 6: TalkToMe otherComponent;
otherComponent
is declared to store a value of type TalkToMe
TalkToMe
Component object will be created and stored in the variable otherComponent
Line 10: otherComponent = GetComponent<TalkToMe>();
Start()
method which Unity calls only once to initialize variables.GetComponent<T>()
method is called to retrieve a reference to the TalkToMe
Component object. This is item 3 on the previous graphic under the section, Accessing another Component on the current GameObject.<T>
part is the type of Component, the class name, that the method will return.otherComponent
. Why?So that every time we need to use the TalkToMe
Component with Dot Syntax, we can just use the reference stored in otherComponent
instead of having to use GetComponent<TalkToMe>()
each time.Line 19: Debug.Log("This is the TalkToMe Component: " + otherComponent);
Line 20: Debug.Log(otherComponent.hereItIs);
hereItIs
of the TalkToMe
Component object. This is item 4 in the graphic under the section, Accessing another Component on the current GameObject.hereItIs
variable is declared on line 6 of the TalkToMe
class.hereItIs
is public
so that it can be accessed from other scripts.otherComponent
, we would have written the Dot Syntax expression like the following line of code:GetComponent<TalkToMe>().hereItIs
Line 21: otherComponent.MakeMeTalk();
On TalkToMe
:
Line 8: public void MakeMeTalk()
MakeMeTalk()
method is public
so that it can be called from other scriptsLearningScript
classOn LearningScript
:
Line 22: }
3.135.201.217