2D collision not being detected?

I have my player moving through the map with this:

transform.Translate(xSpeed, ySpeed, 0);

I have added a rigidbody2d with 0 gravity and a box collider to the player. I then added a cube and spread it out across the track, and added a box collider to this and tagged it as “enemy”, and the player passes through this as they travel through the map.
I have tried this:

void OnCollisionEnter2D(Collision2D col) 
{
    if(col.gameObject.CompareTag("enemy"))  
    {
        Debug.Log("Hello");
    }
}

As well as:

void OnCollisionEnter2D(Collision2D col) 
{
    if(col.gameObject.CompareTag("enemy"))  
    {
        Destroy (gameObject);
    }
}

However nothing happens with either of these. Any ideas would be appreciated. Thanks

  • Firstly, if you’re using 2D physics you need a BoxCollider2D component, not a BoxCollider.
  • Secondly, don’t move the object with transform.Translate. This will “teleport” the object and not respect physics collisions. Use Rigidbody2D.MovePosition instead - Unity - Scripting API: Rigidbody2D.MovePosition
  • Thirdly, when debugging collision problems, always use Debug.Log to check that the tag of the thing you’re colliding with really is “enemy” and not, say, “Enemy”…