0
votes

I am trying to make an object that upon collision with another object, gets destroyed. I have also used Debug.Log and it turns out that the collision is not even detected. Here is the code

     public class Enemy_1 : MonoBehaviour
 {
     public void OnCollisionEnter2D(Collision2D col)
     {
         if (col.gameObject.tag.Equals ("AttackArea"))
         {
             Destroy(gameObject);

         }
     }
 }
1
Do your objects have Rigidbody2D components and Collider2D? - derHugo
Also, check your collision detection type. You could try changing it to Continuous. Also, the Havok Physics is supposed to be faster. That might be fun to try. - jiveturkey
instead of string comparing rather use col.gameObject.CompareTag("AttackArea") to avoid silent fails for typos - derHugo

1 Answers

0
votes

Welcome to the community!

To allow us better to understand the context, next time provide some inspector screenshots of these objects. It will be easier for both of us! 😋

Now, for your problem, there might be one (or combination) of few reasons:

  1. None of the two objects have Rigidbody2D attached. For collision to be detected, at least one of two must be a Rigidbody2D. ...
  2. Other object is not tagged as AttackArea. Thus, tag equation returns false. ...
  3. Other object's collider is marked as is trigger. In this case OnTriggerEnter2D(Collider2D) is called instead of OnCollisionEnter2D(Collision2D).

Check for each of these and let us know! 😉