Communication between Scripts — Examples in Unity

Introduction

In this arti­cle we see how to CALL FUNCTIONS and READ VARIABLES that are defined in a dif­fer­ent script in Uni­ty. This is espe­cial­ly impor­tant to cre­ate object-ori­ent­ed solu­tions, because being able to access oth­er scripts allows us to cre­ate scripts that solve spe­cif­ic prob­lems and work with oth­er scripts to achieve a big­ger result, sep­a­rat­ing respon­si­bil­i­ty, increas­ing abstrac­tion. In addi­tion you will also find two videos about call­ing func­tions and read­ing vari­ables from anoth­er script in Unity.

Videos on this topic:

How to CALL A FUNCTION from another script in Unity


How to READ A VARIABLE from another script in Unity

Interaction between scripts — A couple things to keep in mind

Let's look at a list of items to keep in mind to under­stand the basis behind the inter­ac­tion between scripts.

About the Scripts

In this case we are going to see an exam­ple in Uni­ty, there­fore the two Scripts we are going to use will be an exten­sion of the MonoBe­hav­iour class. This, in prac­ti­cal terms, means that when the game starts, a "Start" func­tion will be exe­cut­ed and also in each frame of the game an "Update" method will be auto­mat­i­cal­ly executed.

About the execution of Scripts

In order to exe­cute the code that we will include in our scripts, those scripts must be assigned to at least one "GameOb­ject" in the hier­ar­chy of the scene we will run. In pro­gram­ming, there must exist an Instance of the class defined in the Script.

Instances of a classes

When we add the same Script to two dif­fer­ent GameOb­jects we are cre­at­ing two sep­a­rate instances of the class, i.e. two objects that are going to be sim­i­lar because they come from the same class, but their inter­nal state will not nec­es­sar­i­ly be the same all the time.

Having the reference of an object

This is one of the key points to pay atten­tion to and try to under­stand in depth.

Objects in pro­gram­ming are instances of a cer­tain class and in order to access its func­tion­al­i­ty, that is to say read its pub­lic para­me­ters or exe­cute its pub­lic func­tions, we must have the ref­er­ence of the object we need to use, in oth­er words find the object among all the oth­er objects that exist in the program.

The Dot Operator

The dot oper­a­tor in sev­er­al pro­gram­ming lan­guages allows us to access the pub­lic fields and meth­ods from an object. In oth­er words, if we have the object ref­er­ence, we can apply the dot oper­a­tor to it in order to exe­cute any of its pub­lic meth­ods or read and write any of its pub­lic fields.

Practical example of Interaction between Scripts in C# — Unity

Previous Steps

In any Uni­ty project we cre­ate two Scripts, Scrip­tA and ScriptB, in the first one we define the func­tion that will be exe­cut­ed from the sec­ond Script.

c sharp scripts that communicate with each other in unity
Fig. 1: We cre­ate two scripts called Scrip­tA and ScriptB.

In the hier­ar­chy we are going to cre­ate two emp­ty GameOb­jects to be able to cre­ate instances of both Scripts.

hierarchy of a project in unity, gameobjects
Fig. 2: Cre­ate two Emp­ty GameOb­jects in the hier­ar­chy to con­tain both Scripts.

In GameOb­jec­tA we add the Scrip­tA as com­po­nent and in GameOb­jectB the ScriptB. We can do this from the inspec­tor with the "Add Com­po­nent" but­ton or by drag­ging the script to the inspec­tor of the GameObject.

add component button to add components to the gameobjects in unity
Fig. 3: Select object A and in the inspec­tor, using Add Com­po­nent, add Scrip­tA to its components.
inspector of a gameobject in unity, drag and drop of components
Fig. 4: Anoth­er way to add com­po­nents is to drag them direct­ly into the GameOb­ject inspector.

Code inside the Scripts

Let's write the instruc­tions we'll use to per­form the inter­ac­tion between Scripts.

When you cre­ate a new Script in Uni­ty, it will come with some func­tions pre­de­fined, as you can see in fig­ure 5. The "Start" and "Update" method, which will be auto­mat­i­cal­ly exe­cut­ed if the Script is assigned to at least one GameOb­ject from the hierarchy.

c sharp default scripts in unity
Fig. 5: We open both Scripts in some edi­tor. We can see some code already written.

Functions and Variables from "ScriptA"

In the first Script we are going to write the fol­low­ing code:

communication between two scripts in unity, a script executes a function defined in another script
Fig. 6: Fields and meth­ods belong­ing to Script A.

A pub­lic string called "name" that will help us iden­ti­fy which instance it is.

Two meth­ods, one called "Function1" and the oth­er "Function2", the first func­tion we will define it as pub­lic and the sec­ond pri­vate, lines 10 and 16 respec­tive­ly from fig­ure 6.

We will be able to access the "Function1" method through the dot oper­a­tor because it was defined with pub­lic vis­i­bil­i­ty. , as it's defined as public. 

As we can see in fig­ure 6, "Function1" prints in con­sole the result of the exe­cu­tion of "Function2". This method returns a text that will allow us to see who is the object that is exe­cut­ing the "Function1" method and which instance of the Scrip­tA class it is.

Functions and Variables from "ScriptB"

The "ScriptB" script will be the one that calls the func­tion defined in the oth­er Script A. In fig­ure 7 we see the instruc­tions defined in the "ScriptB" script.

communication between two scripts in unity, a script executes a function defined in another script
Fig. 7: Fields and meth­ods belong­ing to Script B.

We define a string to assign a name and know which instance it is.

To be able to exe­cute func­tions defined in anoth­er Script we must have the ref­er­ence of the instance of that class. So let's define a Scrip­tA type vari­able and name it "scrip­tA" (first let­ter with low­er­case), as we see in line 13 of fig­ure 7.

Here we only have half of the work done, we declared the
"A" vari­able inside "B", but this vari­able is emp­ty (a null vari­able) and will remain emp­ty unless we do some­thing about it.

To find the ref­er­ence of an object in a Script there are sev­er­al ways, in this case I will use a func­tion calle "FindObjectOfType<T>" where "T" is the type of the vari­able we want to find. This func­tion will search in the hier­ar­chy an object of the indi­cat­ed type and return the ref­er­ence of that object if it founds it. See line 18 of fig­ure 7.

More meth­ods to FIND REFERENCES in Unity

Now that we have the ref­er­ence of the "A" object, inside "B" we can exe­cute the "Function1" func­tion that is defined inside the A Script. Line 20 from fig­ure 7).

Dot Operator

As men­tioned before, the dot oper­a­tor will allow us to access all the fields and pub­lic meth­ods defined with­in the class.

In fig­ures 8 and 9 we see that using the ref­er­ence of the Scrip­tA-type object fol­lowed by a dot, we can see the list of fields and meth­ods that are avail­able to use.

In fig­ure 8 we see the "name" vari­able that was the pub­lic string defined inside "Scrip­tA" and in fig­ure 9 we see the "Function1" method, also defined as pub­lic. We can't see the "Function2" method because it was declared as pri­vate.

operator point to access fields and public methods defined in a script, basic programming, unity
Fig. 8: The dot oper­a­tor allows us to read and write the "name" field, which is a string defined as public.

operator point to access fields and public methods defined in a script, basic programming, unity
Fig. 9: The point oper­a­tor allows us to exe­cute the "Function1" method defined as public.

First exectution test

Before enter in the Play mode, we select GameOb­jects "A" and "B" from the hier­ar­chy and write names in the "name" fields to be able to ana­lyze the exe­cu­tion of our code.

The "Scrip­tA" instance will be called "George (A)" and the
"ScriptB" instance will be called "Mike (B)", as we see in fig­ures 10 and 11.

inspector of a gameobject in unity, scripts that communicate with each other, basic programming in unity
Fig. 10: In the GameOb­jec­tA inspec­tor, we put a name to know that it is that instance of the Script A class.

inspector of a gameobject in unity, scripts that communicate with each other, basic programming in unity
Fig. 11: In the GameOb­jectB inspec­tor, we put a name to know that it is that instance of the Script B class.

When enter­ing in the Play mode we see in the inspec­tor of GameOb­jectB that the "Scrip­tA" field shows an object (unlike fig­ure 11 where it said "none"). This means that the "ScriptB" was able to find the "Scrip­tA" ref­er­ence.

Fig­ure 13 shows the on-screen mes­sage, print­ed by the Scrip­tA Function1 method, which was called from the ScriptB. 

The mes­sage says: "Mike(B) has exe­cut­ed my Function1. I'm George(A), by the way.

inspector of a gameobject in unity, scripts that communicate with each other, basic programming in unity
Fig. 12: When run­ning the game, the Scrip­tA object ref­er­ence is found due to the Find­Ob­jectOfType<> instruction.

print console messages in unity, scripts that communicate with each other, basic programming unity
Fig. 13: This mes­sage is print­ed because a method defined in Scrip­tA is exe­cut­ed from the ScriptB.

Second execution test

Let's go a lit­tle deep­er into the con­cept of pro­gram­ming object as an instance of a class. 

Choose GameOb­jec­tA from the hier­ar­chy and add a sec­ond instance of the Scrip­tA class using the "Add Com­po­nent" or drag and drop button.

This sec­ond instance will be called "Luke (A)", in fig­ure 14 we see both instances of the class.

inspector of a gameobject in unity, scripts that communicate with each other, basic programming in unity
Fig. 14: A sec­ond instance of the Scrip­tA class is added to the GameOb­jec­tA with a dif­fer­ent name.

When run­ning the game as it is, we see in the con­sole that Mike (B) has exe­cut­ed the Function1 method of Luke (A), see fig­ure 15.

What has hap­pened here is that the "Find­Ob­jectOfType<>" func­tion in line 18 of fig­ure 7, has found a dif­fer­ent ref­er­ence of a Scrip­tA type object than before, the "name" vari­able from this ref­er­ences is "Luke (A)". A dif­fer­ent instance of the same class as the one that has the text "George (A)" in its "name" variable. 

print messages in console in unity, communication between scripts, basic programming unity
Fig. 15: When run­ning the game we now see that the Function1 method of the instance called Luke is being executed.

Now lets mod­i­fy the code in "ScriptB" so that it is able to find all the "Scrip­tA" ref­er­ences in the scene and exe­cute the "Function1" method of each one of them.

c sharp script that executes functions defined in other scripts, e.g. in unity, communication between scripts
Fig. 16: We mod­i­fy the ScriptB in this way so that it exe­cutes the func­tions of the two instances of ScriptsA.

In the object dec­la­ra­tion we have now defined an array (or vec­tor) of "Scrip­tA" type objects (line 13 fig­ure 16), this means that we will be able to save sev­er­al ref­er­ences of Script­sA objects.

In line 18 of fig­ure 16 the change is rather sub­tle, instead of run­ning the "FindObjectOfType<T>" func­tion we use "FindObjectsOfType<T>", this oth­er func­tion returns all the ref­er­ences of the indi­cat­ed "T" type that is able to find in the hierarchy.

The last thing we do is go through all the ele­ments of the array using a fore­ach loop and we exe­cute the "Function1" method to all of them, as can be seen in lines 20 to 23 of fig­ure 16.

inspector of a gameobject in unity, scripts that communicate with each other, basic programming in unity
Fig. 17: When run­ning the game we see that the two ref­er­ences of the Scrip­tA objects are found and we have them stored in the array.

When enter­ing again in the Play Mode, we see that now in the GameOb­jectB inspec­tor we have the "Scrip­tA" object ref­er­ences (fig­ure 17) inside an array of size 2.

And now in the con­sole appear two mes­sages, the first cor­re­sponds to the exe­cu­tion of Luke's "Function1" method and the sec­ond to the exe­cu­tion of George's "Function2" method.

print messages in console in unity, communication between scripts, basic programming unity
Fig. 18: In the con­sole we see that the Function1 meth­ods of each Scrip­tA object are executed.

Third execution test

We are going to mod­i­fy the ScriptB again to see anoth­er way to obtain the ref­er­ences of the objects and thus to be able to call their func­tions from anoth­er Script.

In this case, in the "ScriptB", we are going to declare two seri­al­ized "Scrip­tA" objects (they can also be pub­lic, the idea is that they appear in the inspec­tor). These objects will be called "scrip­tALuke" and "Scrip­tA­George".

Then in the Start method we are going to exe­cute the "Function1" meth­ods direct­ly using these objects. In this case it is not nec­es­sary to find the ref­er­ences through code since we will assign them direct­ly in the inspec­tor.

The mod­i­fied "ScriptB" is shown below. 

c sharp script that executes functions defined in other scripts, e.g. in unity, communication between scripts
Fig. 19: We mod­i­fy the ScriptB in this way to try anoth­er way of hav­ing the ref­er­ence of the objects.

In the inspec­tor we can see the new fields for "Scrip­tA" objects (fig­ure 20).

inspector of a gameobject in unity, scripts that communicate with each other, basic programming in unity
Fig. 20: In the inspec­tor we have fields for two Scrip­tA objects.

We will mod­i­fy a lit­tle the GameOb­jects of the hier­ar­chy, we will have an Emp­ty GameOb­ject called A‑Luke and anoth­er called A‑George.

hierarchy of a project in unity, gameobjects
Fig. 21: Instead of the GameOb­jec­tA we will have two emp­ty GameOb­jects for each instance of the Scrip­tA class.

In each GameOb­ject we assign the Scrip­tA com­po­nent and com­plete the cor­re­spond­ing name, see fig­ures 22 and 23.

inspector of a gameobject in unity, scripts that communicate with each other, basic programming in unity
Fig. 22: In the GameOb­ject A‑Luke we add the Scrip­tA com­po­nent and enter the cor­re­spond­ing name.

inspector of a gameobject in unity, scripts that communicate with each other, basic programming in unity
Fig. 23: In the GameOb­ject A‑George we add the Scrip­tA com­po­nent and enter the cor­re­spond­ing name.

Now let's take the GameOb­jects from the hier­ar­chy and assign them in the cor­re­spond­ing fields of the "ScriptB"

hierarchy of a project in unity, gameobjects
Fig. 24: With these GameOb­jects we will drag and drop in the ScriptB fields.

In fig­ures 25 and 26 we see that the ref­er­ences have been assigned man­u­al­ly, this means that we can exe­cute the "Function1" meth­ods from each instance.

inspector of a gameobject in unity, scripts that communicate with each other, basic programming in unity
Fig. 25: We can assign the GameOb­ject direct­ly to the cor­re­spond­ing field when­ev­er there is such an object among its components.

inspector of a gameobject in unity, scripts that communicate with each other, basic programming in unity
Fig. 26: The ref­er­ences of both Scrip­tA objects have been assigned to the cor­re­spond­ing fields.

In con­sole we see that the mes­sages are print­ed due to the exe­cu­tion of "Function1" method on both instances.

print messages in console in unity, communication between scripts, basic programming unity
Fig. 27: When run­ning the game we see that the Function1 meth­ods of both instances are executed.

Before fin­ish­ing I would like to change the order of exe­cu­tion of the Function1 meth­ods in the ScriptB, as seen in fig­ure 28.

c sharp script that executes functions defined in other scripts, e.g. in unity, communication between scripts
Fig. 28: Reverse the order of the instruc­tions and per­form anoth­er test.

When we do this and enter in the Play Mode again we see that the mes­sages on the con­sole switch places, fig­ure 29.

print messages in console in unity, communication between scripts, basic programming unity
Fig. 29: We see that the mes­sages change the order of appear­ance in the console.

Conclusion

We have seen how to call func­tions that are defined in oth­er Scripts. This is only pos­si­ble if the func­tions are declared with pub­lic vis­i­bil­i­ty, this allows the access from exter­nal con­texts.

In addi­tion we must have the ref­er­ence of the object that con­tains that method to exe­cute, this can be achieved in sev­er­al ways, in this arti­cle we saw three ways to do it. It's impor­tant to under­stand the con­cept of instances in pro­gram­ming, it can be two or more instances of the same class and there­fore mul­ti­ple objects with the same func­tion defined but the result of the exe­cu­tion of that func­tion on each instance could be different.

Under­stand in depth the con­cept of object in pro­gram­ming, which is the instance of a class and the fact that in order to access anoth­er object we must have the ref­er­ence of that object, allow us to build more com­plex solu­tions, sep­a­rat­ing respon­si­bil­i­ty, increas­ing the abstrac­tion of our solutions. 

Scroll to Top
Secured By miniOrange