- Home /
GameObject doesnt get destroyed onCollision
Hey, if my bullet hits my player he isnt dying. I put collider on both and wrote this code:
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Bullet")
{
Destroy(collision.gameObject);
Destroy(gameObject);
}
}
I also wrote a code that the bullet hits the player. But on collision the player isnt getting destroyed. I also tried it with OnTrigger.
Thanks:)
Answer by lastnoob765 · Jul 31, 2021 at 08:30 AM
Make sure either the bullet or the enemy has a rigidbody,you don't need to use gravity,rigidbody is just there for detecting collisions. And use CompareTag("Bullet") method instead of collision.gameObject.tag == "Bullet" . Because the second one produces memory garbage that is gonna affect your game performance and CompareTag() doesn't produce memory garbage so its a better choice. So this is what you shoud do: •Add a rigidbody to bullet or enemy and disable gravity if you don't need it,just tweak the settings so it doesn't affect the behaviour of enemy or bullet(Ai,movement,bulletScript,etc) •And make sure to use CompareTag() method End result should be like this:
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Bullet"))
{
Destroy(collision.gameObject);
Destroy(gameObject);
}
}
Hope it works!
Answer by yashverma30115 · Jul 31, 2021 at 06:10 AM
Which GameObject do you attach this script to . Player or Bullet? if it is on bullet, It is not gonna work!
Make sure that the bullet and player has BoxCollider2D component attached. and also check that your tag has a Capital B like "Bullet" not "bullet".