Detect collision with a specific object in Unity 3D C#

By Faruque Ahamed Mollick

In the gaming world, we often may need to detect the collision between two objects. For example, in many games, we attack our enemies with the bullet. Our enemies destroy in the game because there is a collision detection between our enemy and bullet.



Of course, you may realize that detecting collisions is a quite important part in game development. So, in this tutorial, I am going to show you how to detect collision between two objects so that you can apply it to your game development project.

Here we are going to detect collision with a specific object in Unity 3D with C# programming.

The Unity game engine already provides the collision event API or function which is OnCollisionEnter. We can use it in our C#. Below is the syntax to perform and execute the code after the collision:

void OnCollisionEnter (Collision targetObj) {
    // Our code goes here
}

Inside the OnCollisionEnter function, we can perform our task.

For example, if we want to destroy a particular game object after the collision, we can do it just by detecting the object by its tag name. So first we have to set a tag for our object which we want to destroy.

You can easily set a tag for that specific game object just by selecting it, Go to the inspect and select tag drop-down box. Then from the drop-down list, click on Add Tag…

See the picture below to know where the tag option is available:

Unity Game Object Tag

After we set a tag for the object, we can detect the specific object by its tag name. We will first check if our game object has the specified tag name and then destroy it on Collision with another Object.

Below is our C# code to detect collision with a specific object in Unity:

void OnCollisionEnter (Collision targetObj) {

if(targetObj.gameObject.tag == "Resistance")
  {
        Destroy(targetObj.gameObject);
  }

}

 

In the above code, we first check if the object has the tag name with the if statement:

if(targetObj.gameObject.tag == "Resistance")
{
  // Run the code if has the tag name
}

Inside the statement, we have passed the code to destroy the object with the tag name:

Destroy(targetObj.gameObject);

So we have successfully able to detect collision with an object by its tag.

 

Leave a Reply

Your email address will not be published. Required fields are marked *