Script communication in Unity using GetComponent.

Now that we have our player shooting lasers and our enemies spawning; as shown below; how do we go about making the colliders on these objects interact?

Is Trigger is ticked on our player and the enemy and laser prefabs, so since there is no scripts telling the objects how to interact they pass through one another.

When developing a program, variables are stored in the memory at different locations. If an object could see any other object members, there would be a risk to modify them even though it was not intended. There are various way to access variables, one of those ways is by using GetComponent.

In order to use GetComponent, we need to be able to identify which object the component we are after is on. An easy way to do that is through the use of something called Tags.

Set the Tag of Player in the Inspector to Player, same for Enemy and Laser.
If the collider entered has the tag “Player”.

In order to access ; let’s say the script Player attached to our Player object; we first need to create a reference to that script. This is where GetComponent comes in.

Set a Data type Player variable player equal to the Component called Player attached to the other transform with tag “Player”.

Now that we have a reference to the component we are after, we can access any public method within that script.

We can now access the Damage method in the player script by typing player.Damage(); within the if statement.

In order to avoid possible null reference exceptions when running our game, it is best practice to check that the component we are after exists. We can do this by performing a check using; in this example; if(player != null), before trying to use a method within it.