- Home /
Not destroying clone after interacting with other gameobject
Hello folks! I am creating a top-down shooter and I just set up shooting but when my bullets hit the enemy it doesn't destroy it or the enemy.
public class bullet : MonoBehaviour
{
public GameObject enemy;
private void OnCollisionEnter2D(Collision2D collision)
{
Destroy(gameObject);
Destroy(enemy);
}
}
Is it the full code ? The variable enemy
is not defined. You should destroy the enemy before the gameobject. Do you use 2D RigidBody and 2D colliders as well ?
This is the full code for the bullet. I just switched those around and I do have 2D rigidbodys and circle colliders. Do you want me to put in the code for spawning the bullet if that will help at all?
Also I get now feedback whatsoever with these I even put in a Debug.Log and that still didn't show anything :/
Answer by kurizu · Sep 27, 2019 at 04:08 PM
I think you misinterpreted the OnCollisionEnter2D function. The object that your bullet collides with is returned as the collision parameter in the function, so if you want to remove that object, you will have to do; Destroy(collision.gameObject).
In order to have objects detect collision in the first place, you will also need to have a Rigidbody on 1 of the objects and obviously a 2d collider on both. Also, you should first do a check if the object your bullet is colliding with is an enemy, so consider putting a tag on your enemies.
Your answer
Follow this Question
Related Questions
[Problem] Cant activate 2D objects with touch? 1 Answer
Finding any objects below or above object at ANY POINT? 1 Answer
Getting a Raycast rope to follow its object 0 Answers
2D Character Controller Movement Issues 0 Answers
onGround raycasts return onGround is true while colliding with platform sides 0 Answers