Communicating between C# Scripts in Unity

When creating your game in Unity, most of your C# scripts will generally be linked to an object. Because these scripts include different types of information, you may sometimes need these scripts to communicate between each other.

So. let’s say that you have two different scripts Script1 and Script2, each linked to the objects Object1 and Object2, respectively.

  • The content of Script2 could be as follows:

 

public class Script2 : MonoBehaviour 
{
	private string firstName;
	void Start()
	{
		firstName = "John";
	}
	public  string getFName()
	{
		return (firstName);
	}
}

In the previous code:

  • We declare a string variable called firstName and it is private, so it will only be accessible from instances of the class Script2.
  • We initialize the variable firstName in the method Start.
  • We then declare a method called getFName that returns the value of the member variable firstName; note that this method is public and it will therefore be accessible throughout our game.

We could create a new script called Script1 that will access the other script Script2.

The content of Script1 could be as follows:

 


void Start () 
{
	string nameFromTheOtherScript = GameObject.Find ("Object2").GetComponent<> ().getFName ();
	print ("name is " + nameFromTheOtherScript);	
}
void Update () {}

In the previous code:

  • We create a new string variable called nameFromTheOtherScript.
  • We access the method called getFName from the script Script2, that is a component of the object called Object2.
  • We then save the value returned by the method getFName in the variable called nameFromTheOtherScript.

So, based on the previous steps, we just need to remember that:

  • A script, when attached to an object, is seen as a component; it can, therefore, once we have identified the corresponding object, be accessed using the method GetComponent.
  • If methods or variables that belong to this script are public, they should then be accessible from outside the script.

Using this approach, we could access attributes of any of the components (including scripts) linked to a particular objet.

Related Articles: