Communication Between Scripts In Unity Using GetComponent

Script communication is arguably one of the most important and most struggled with aspects of programming for new developers. But by learning and understanding how this works, you will be opening yourself up to a world of possibilities in the world of code.

How does it work?

Well to start, you cannot communicate with another script unless you can access the object to which it’s attached. If your scripts are on the same object, then the process is as simple as a few lines of code. But if they are on different objects, you’ll have to create a reference to the other object.

Ok, but how do I use it?

Well, it depends.

If you are using one script to try and access another script that's attached to the same object.

Just “Cache” the second script and give it a name. Then define the name in the Start() or Awake() method by calling the second script’s component.

Otherwise, if you’re trying to access scripts that are attached to different objects in the scene.

You’ll need to create a reference to the other objects somehow. This can be done in a few different ways!

You can create a direct link to the other gameobject in the hierarchy.

Create a “public GameObject” and cache the object that holds the other script in the inspector. Then just create a second variable to cache that object’s script component.

Or you can search the hierarchy for an object by its name.


Keep in mind that spawned prefabs will enter the hierarchy with “(Clone)” at the end of their name which must be accounted for if you plan to find it by its name!

Or you can search the hierarchy for an object by its “Tag”.

Hi, my name is Adam Reed and I am a software engineer specializing in Unity and C# development. Feel free to scroll through and check out some of my work!

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