Script communication in Unity

Daniel Kirwan
2 min readMar 31, 2021

At some point in your game development in Unity, you will need to communicate from one script to another to update some variables, like the player stats, to take away health or increase the player speed.

It is bad practice to directly manipulate the variable you need updating, so in my case, I will be calling a method in the Player script that will be responsible for updating the variable for the player lives.

For other scripts to be able to access this method it needs to be set to public. If it is set to private then only the player script will be able to run that method. This is not the functionality that I require, I will need the enemy script to update the lives when it detects that it has collided with the player. I will then call the public void Damage method and it will handle the updating of the player lives.

To be able to communicate together we first need to get a reference to the script that we want to communicate with.

The first line of the method is where I am checking if the object triggering the collision is the Player. Due to the collision we already have access to the Player object in this method called ‘other’. We then need to access the transform with the dot operator . and then we can get the component that we need.

Player player = other.transform.GetComponent<Player>();

I am then saving a reference to the component on that game object called Player. And this is referring to the Player.cs script component.

Player script component

This then allows me to call the public Damage method inside the Player script.

If you remember from above, the Damage method is decrementing the _lives variable. This means that it is decreasing the variable by 1 every time that it is being called. If the _lives variable is less than 1, then the player is destroyed and the game is over.

And that is it for script communication in this article.

--

--