Script Communication in Unity using GetComponent
Objective: How to use Script Communication and utilize GetComponent.
Today in our Space Shooter we want to introduce a damage method to communicate with our player. Unfortunately script communication is hard for New Comers in Unity to understand. To communicate with are script were gonna use GetComponent to access these scripts related to our damage method. First thing were gonna do is create a custom method called public void Damage() outside of the script which is responsible for damaging the player. Also it’s important we don’t keep this class method private because we want it to communicate with our enemies in our custom method. So the custom method will be public for that reason. Now we are gonna introduce a concept now called GetComponent. The only component you have direct access to in Unity is the transform of the object. To access any other component you need to use GetComponent. The only other way to access another object is to tell Unity what component you are looking for and in this case its the player script which contains our damage method. To access objects in Unity you type other.transform.GetComponent<Player>().Damage(); this is accessing our player and our Damage custom method. Another way you can use GetComponent is by Null checking if the player is null before calling the damage method from the script . The way you do is like this , declare the the type of component in this case it would be player and then player again , followed by other.transform.GetComponent <> and check the condition. This is Script Communication and GetComponent in a nutshell.