Script Communication in Unity using GetComponent
Day 12- Making 2D Space Shooter Game
When creating your game in Unity, most of your C# scripts will generally be linked to an object. Because these scripts include different types of information, you may sometimes need these scripts to communicate between each other.
Communication between Scripts is an informal name for this problem, it means that being in one Script we will be able to access another Script.
As you can see in the image above, whenever the enemy enters the player trigger, it access the Player component(script) inside the Player gameobject using the information provided by other(gameobject) and you call a public method Damage() which is inside Player script.
Its better to communicate as above by checking if the player component returns null or not to avoid possible errors during runtime. Let’s say there is no player script inside the other gameobject which is going to generate a ‘Object reference not set to an instance of an object’ error. So it is better to check if the component is null or not before accessing the variables and function inside.
Also note that you can only access and use public variables and functions and not private or other access modifier types. You can also use other scripts by creating variables for other gameobjects as well.