I want my bullet to get destroyed OnTrigger, however it doesn't get destroyed but that Debug.Log works fine. I have tried everything such as rewriting the script, replacing it and attaching it over and over again. Could somebody help me?
Here's my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
public GameObject Bullet;
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Bullet"))
{
Debug.Log("I die");
Destroy(gameObject);
}
}
}
CodePudding user response:
You're destroying the Enemy
gameObject. To also destroy the bullet, try the code below:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
public GameObject Bullet;
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Bullet"))
{
Debug.Log("I die");
Destroy(gameObject); // destroying self object (Enemy Object)
Destroy(collision.gameObject); // destroying collided object (Bullet Object)
}
}
}
CodePudding user response:
If you want to destroy the bullet you should pass the bullet object as an argument to the function Destroy(), but you are passing the enemy object.
replace Destory(gameObject) with Destroy(Bullet).
Or if you want to destroy the bullet that get triggered replace it with : Destroy(collision.gameObject)