Destroy object on touch of object with specific class

I need to know how to destroy a 2d object named enemy with the enemy when a 2d object named bullet with the bullet tag hits it. I am also new, please explain things as much as you can.

OnCollisionEnter2D is the function you might want to use.

  1. In your bullet class, you would add this void OnCollisionEnter2D function (below).
  2. Then, you’ll need to add some kind of Collider on your bullet (Box Collider 2D most likely) and set the Collider in your inspector to isTriggered.
  3. Finally, you’ll need Colliders on your objects you’ll want to destroy. So that when your bullet collides with the object, the below function will get triggered.

This 5 min video might also help you. (1)

void OnCollisionEnter2D(Collision2D coll)
    {
        UnityEngine.Debug.Log("Colliding on object: "+ coll.gameObject.tag);

        if (coll.gameObject.tag == "Your tagged item")
        {
            Destroy(coll.gameObject);
        }
    }

An easy way to do it is check in the bullet’s Update loop to see whether or not it is close to the other object. This works well if you have a way to loop through all the objects that the bullet could be hitting.

In bullet’s script:

void Update(){
    float distance = Vector3.Distance(transform.position, object.transform.position);  //object is the object you want to check for hit
    if (distance < .05f) {  //some small number
        Destroy(object);
    }
}

Another way to do it which spares you the hassle of getting a list of objects to check is using a trigger collider with the OnTriggerEnter method on the object:

void OnTriggerEnter(Collider other){
    if (other.gameObject.CompareTag("bullet")){
        Destroy(gameObject);
    }
}

some scribble ideas
void OnTriggerEnter(Collider otherThing)
{
if (otherThing is Component)
{
MyClass = otherThing.GetComponent();
MyClass.doSomething();
}
}

//some other idea also
 //private Character myCharacterDefinedinHeaderAsInstance;
  //later....

private void OnCollisionEnter(Collision col)
     {
         if (col.gameObject.GetComponent<Character>())
         {
             Debug.Log("Character Hit");
             myCharacterDefinedinHeaderAsInstance = col.GetComponent<Character>();
            myCharacterDefinedinHeaderAsInstance.doSomething();
         }
     }