Script Communication with GetComponent in Unity

Germán Walden
2 min readApr 20, 2021

--

Objective: Communicate with other script with the GetComponent function in Unity.

Script communication is a core feature in coding. It allows us to get access to another gameobject’s components or modify external scripts when the variables and methods are public.

Asteroid triggers a SpawnManager method when destroyed

For this example, we are going to trigger a public method of our SpawnManager from our Asteroid(when it gets destroyed)

Requisites: An empty GameObject called “SpawnManager” with its spawning implementation and a GameObject Asteroid with its OnTriggerEnter2D method to launch the first wave.

The first step is simple, open the Asteroid script and get the SpawnManager reference.

Declaring the variable above the void Start()
Getting the SpawnManager reference

Remember to type “SpawnManager” or the name of the GameObject you want to find. <SpawnManager> is the name of the script it has attached to. With GetComponent we can access the script or whatever component the GameObject contains: Transform, Colliders, Rigidbody, etc…

Now that we have the reference in our Asteroid, we need to trigger the public method that belongs to the SpawnManager

The public method on the SpawnManager

In this case, when the Asteroid collides with the laser, we want to begin the first wave of the game and start spawning the enemies, for this we will call the method from the Asteroid.

OnTriggerEnter2D to get the collision reference.

And that would be it for a full script communication cycle. Remember that the method you wanna call, or the variable you wanna modify has to be public!

--

--

Germán Walden

Passionate Unity developer always looking for new challenges!