Hparsons28
Hparsons28

Reputation: 87

Unity: 2D Collision Detection Using Tags

void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.tag == "Bullet")
    {
        Destroy(gameObject);
        Debug.Log("hit");
    }
}

This is my code, I appreciate that there is a lot of other sources out there however I have looked on the internet and just cannot understand where im going wrong. I know its probably something so small. I'm attempting to get on collision detect destroy "this" game object using the tag. The Bullet prefab has the Bullet tag and is spelt exactly the same, both gameObjects have both a rigidbody and a 2D box collider.

Any help will be great.

Upvotes: 1

Views: 20330

Answers (2)

Caio Mar
Caio Mar

Reputation: 2624

Better practive is to use CompareTag instead:

private void OnCollisionEnter(Collision other) {
    if(other.gameObject.CompareTag("Ground")) {
        isJumping = false;
    }
}

Upvotes: 1

F.M
F.M

Reputation: 66

things to check:

  • Rigibody2D are simulated (in inspector Rigidbody2D simulated check is true)
  • none of the colliders are set to isTrigger
  • because this is 2d so make sure both sprites are on the same layer order or z-order
  • try debugging and check which object is bullet hitting

(and i assume you have Rigidbody2D not Rogidbody like you mentioned in your question)

(if all of these are checked then just for testing try to decrease the speed of bullet, if bullet is going too fast then try changing “Collision Detection” to continues)



most imported thing “debug” and debug before destroying not after

Upvotes: 5

Related Questions