Script Communication with GetComponent in Unity
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.
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.
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
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.
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!