Destroying enemies

Niklas Bergstrand
3 min readMar 27, 2021

Objects colliding is one thing but how do the objects that collide communicate with each other? This is when script communication using GetComponent is used. Below I will go through how to use it in the space shooter.

First create a cube as a simple base for the enemy:

Create and attach a new script to the enemy object and add a fitting material:

Similar to the Projectile script in my previous article, add a variable for speed and set the transform to move downwards:

When the enemy moves outside of the screen we can reuse the object and move it back to the top:

On the enemy game object set the collider to Is Trigger and add a Rigidbody:

To be able to detect collisions, at least one object that is colliding needs to have a Rigidbody. The Rigidbody component does have a small performance hit so it is important that only the object that really needs it has it attached.
The enemy in this case will collide with both the player and the projectiles so it makes sense to only add it to the enemy object.

Add a “Player” tag to the player object and a “Projectile” tag to the projectile object. If you do not have those tags then click on “Add Tag…” in the drop down menu and create the tag there:

In the Enemy script add the function OnTriggerEnter which will get called once when the Enemy object collides with another object:

Open up the Player script and add a variable for player lives:

In the player script also add a public function called DamagePlayer which subtracts one life per call. Add an if statement which checks if _lives is less than or equal to 0. If less, destroy game object:

Back in the Enemy script add two if statements inside OnTriggerEnter. One to check for collider with the “Player” tag and another to check for the “Projectile” tag:

If the tag is “Projectile” then destroy first the projectile object and then enemy game object:

Now we finally get to the part with script communication. Using GetComponent you can access the part of the game object specified between the angle brackets. This can be any script or component attached to the game object. You can then access any public variables or functions on that component. In this instance we call the DamagePlayer function on the Player script:

The whole enemy script:

Good luck!

--

--