Now they talk!?!
Script Communication in Unity using GetComponent
At this point in our space shooter we have enemies, a player and lasers. We want to have the player damage itself when the enemy hits it. We’re checking the collision in OnTriggerEnter on the enemy component, how can we let the player know to take damage?
This is achieved through script communication. In this simple version of the game that communication is accomplished through the use of a public method exposed on the Player class, so that the enemy class can see it, and the GetComponent() function.
GetComponent() allows us to find a component of type T if the gameObject we are checking has one attached. It returns null if the component doesn’t exist on the gameObject. In our case, we are using GetComponent() to try to retrieve the Player script component from the object that collided with our enemy, which in our use case should be the player since we have checked the tag on the object to make sure that it is the player. We then check the result to make sure that it is not null, meaning the gameObject that collided with our enemy does have a Player script component attached to it.
Once we have a reference to our Player script component we can then call the public Damage function that will have our Player execute the code that occurs when it takes damage.
Now we have the ability for our enemy script to communicate with our player script! There are better ways to do this but in our simple game this works for now. In future articles we may look at more advanced ways to accomplish this goal. Tomorrow we will look at coroutines with Unity. If you enjoyed this article, or want to come along with me as I progress on my journey, follow me at gamedevchris.medium.com.