Connecting Scripts in Unity

Matthew Givens
2 min readApr 30, 2021

When building a game in Unity, scripts will often need to communicate with each other. One example is in order to damage a player we may need to call that method from the enemy’s script. However, in Unity we only have direct access to the transform component of another object. In order to use another component we use the “GetComponent” method. In the following example we are in the enemy’s script and require access to the “Player” script.

A common error to look out for when connecting scripts is null reference exception. This occurs when the component you are attempting to access doesn’t exist and you call a method on it. We can prevent this error by storing the component in a reference variable and null checking. Null checking uses conditional logic to only call the method if the required component exists. In this example we store the script “Player” in a variable and only run the “damage” method if the component exists.

--

--

Matthew Givens

A self-taught Unity developer, learning more everyday and documenting my journey. My passion for the world of game development grows with every skill I pick up.