Connecting Scripts in Unity

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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Matthew Givens

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.