Script communication can be a tricky concept for newcomers to Unity and C# so let’s look at this in a use case scenario.
If you’ve been following along, you’ll have a Player you can move around the screen and shoot lasers with. Let’s make something to shoot at, I’m just going to make another cube — a little smaller than our player — give it an Enemy tag, colour it red and make sure the collider is set as a Trigger.
I’m also going to create a new script for the enemy with a public method (so it can be called from outside the Enemy class) that simply calls for the destruction of the enemy — or itself.
With that done, I’m going to make a prefab from this enemy and put 2 more in the scene. To make sure the collisions work correctly, I’ll be putting a rigidbody on my Laser prefab (turning the gravity setting off) and setting the collider as a Trigger.
Now we have our scene set, we need to consider what we want to happen —
Shoot the laser
If the laser hits the Enemy (OnTriggerEnter)
Call the Enemy’s ‘Damage’ method
In the Laser script, we need to call our OnTriggerEnter method and check if what we hit was the Enemy (hence the “Enemy” tag).
Once we’ve confirmed we have hit the Enemy, we need to ‘communicate’ with the Enemy we just hit and call the Damage method in the Enemy script.
We do this by using the ‘GetComponent’ method, it allows us to make a connection with any component that may exist on the target GameObject. Whether that be the Transform, Renderer, Collider or any component attached.
In our case, we’re looking for the Enemy script that is attached to the Enemy we just checked for a collision with.
So here we are declaring a local variable of type ‘Enemy’ — this must match the type of component we are trying to get — called enemy. Then we are reaching out for the Enemy component on our colliding GameObject (other). Once we do this, we have access to any public methods/variables within the Enemy class and can do as we wish with them.
In this case, we want to run the Damage method. Before we try to call the method, we should check that it isn’t null. If we weren’t successful in grabbing the Enemy component — for any multitude of reasons — we need to know before we try to use it else we risk causing errors and potentially crashing our game.
With the null check performed, we can happily call the Damage method and dispose of our maniacal enemy! Go on, give it a go…
Now might be a good time to give your enemies the ability to move down the screen, you can use a method similar to the one used to move the lasers.