Script Communication in Unity Using GetComponent and TryGetComponent

Andrew Crippen
3 min readApr 24, 2021

Script communication is how you get things done in Unity whether it be communicating with a manager class or between an Enemy and a Player.

The simplest way through code is to use GetComponent or TryGetComponent to get a reference to the target script.

Variables or methods that you want to access in the referenced script must be public.

I’ll show how I reference my Player script’s Damage method when an Enemy collides.

Inside my Player class I have a public Damage method that takes an int parameter named damageAmount

Inside my Enemy class in my OnTriggerEnter method which detects when a GameObject collides with it I have it comparing the tag to check if it’s the Player, if it is then I am checking to see if the Player has the Player script component attached with GetComponent.

From there I nullcheck and if player is not null I can then call the Damage method with the amount of damage I want dealt in the parameter.

Now when the Enemy collides with the Player it will call the Damage method from the Player class.

The more performant way to do this is to use TryGetComponent.

TryGetComponent does not allocate memory in the editor like GetComponent does.

This is how it would look using TryGetComponent which is a bool that will return the component if true. You can use the <> brackets like with GetComponent but I prefer to do it in the parameters like shown TryGetComponent(out TYPE NameToBeReturned)

To take it even a step further you could have an IDamageable interface that any object that can take damage inherits and then just check for that interface with TryGetComponent.

My simple IDamageable interface that Player inherits… (An interface is like a contract, it forces the script that inherits it to have the variables/properties or methods implemented or it will give an error)

To have the Player class inherit IDamageable you just add a comma after Monobehaviour and the IDamageable like shown, then add a Health variable and Damage method in the Player class.

Here is how it looks when you use TryGetComponent to reference the IDamageable interface component and then access the Damage method.

Enemy collides with Player
Enemy communicates with Player script and calls the Damage method which removes 1 health

--

--

Andrew Crippen

Unity Developer/C# Programmer for VR, 2d,3d Games and other Immersive Interactive Experiences