Using OnTrigger and Rigidbody 2D to Destroy Game Objects

David Hunter Thornton
3 min readAug 20, 2022

--

How do I destroy enemies when a bullet hits them?

Objective: Describe the syntax and best practices for destroying Game Objects when colliding with another Game Object.

In the last article I broke down Rigidbody 2D and the differences between “OnCollision” and “OnTrigger”. Now we need to actually implement OnTrigger within our Game Objects.

But the first thing I want to talk about is “Tags” in the Inspector. Any Game Object can be given a Tag. And you can even create your own Tags. These tags help Unity identify Game Objects regardless of what the name is. For example, we can give both the Mine and the Enemy object the “Enemy” tag. This simply tells Unity to treat the Mine and the Enemy as the same type of object.

I’ve done the same for both the Player and the Bullet objects respectively.

Next we want to use the OnTriggerEnter2D from the Scripting API as shown above. We’re going to include in the parenthesis “Collider2D other”. This says, “collect information about the other Game Object that you collide with”.

We aren’t going to get into the Player Health and Damage just yet. So for now, let’s settle for using Destroy to delete the enemy.

In this instance “other.tag” is calling to check the object we collided with against the tag we’ve specified.

We need to do the same thing for the Bullet but add to destroy the bullet immediately after destroying the enemy. If you destroy the bullet first, it’ll delete the script with it and leave the enemy behind.

Everything should function now and we officially have a 2D Shmup!

Friendly Reminder: Don’t forget to keep updating your project through GitHub/Git and saving any changes you make to a separate branch. You can check out my other articles to get a breakdown of those steps! Day 1–9

--

--