Script Communication in Unity using GetComponent
As I’ve been working on my Space Shooter project, it’s been on my mind as to how I was going to start having separate GameObjects interact with each other. I explored the first part of this in my previous article, where I discussed the differences between collisions and triggers — now, it’s time to get separate scripts to communicate with each other.
This is where the GetComponent command comes in handy. GetComponent can be used to pull GameObjects or behaviors from different scripts and acts as a bridge of communication.
First, I’m going to define the GameObject that will be interacting. This is going to be between our Player character and Enemy spawn, and I’m currently within the Enemy script. So, I’m going to define the Player.
Now that the player has been defined, I can use the component to create an interaction between the Player and Enemy. The goal here is that when the enemy hits the player, the player will receive damage and the enemy will be destroyed.
To do this, I’m going to be utilizing an if() function.
So the script reads that if our player hits the enemy, they will take damage. Furthermore, the enemy will be destroyed after.