When creating a Unity game, GameObjects will generally have a C# script associated with them. As scripts contain different types of information, they will need to communicate with each other. In this article, we will cover how to communicate with another script.
Public Methods
By default, all methods within a script are private and not accessible by other scripts. So if you intend for a method within your script to be accessible, you will need to make it public.
public void Health()
GetComponent
For a script to access a public method within another script, we use the GetComponent class. It returns the first Component found in an undefined order, of the type specified.
Player player = GameObject.Find(“Player”).GetComponent<Player>();
Above, we have created a variable called player of type Player. We have located the GameObject named “Player” by using the method GameObject.Find(“Player”) and then used the GetComponent<Player> to specify the Component we need.
The best practice is to Null check that the Component exists before performing any actions to avoid errors.
if (player != null)
{
player.Health();
}
You can also Null check and report an error
if (player == null)
{
Debug.Log("Player is null!");
}
I hope this article has helped you communicate effectively between scripts.