- Home /
Destroy a gameobject
Hello, I am new to Unity so please be patient with me. I am trying to create a game where you have objects moving across the screen and your player character shoots projectiles. I want to make it so if the projectile hits the enemy object, the shot and the enemy will be destroyed. On both objects I used a rigid body and I gave the enemy a tag, "Enemy". In the code for the shot, I am trying to use the onCollisionEnter2D function and have it search for the object by tag. It then calls DestroyObject to destroy the shot. The code is not working as the shot passes through the enemy object. I am wondering if anyone can help me figure out a solution? The code for the shot is below.
using UnityEngine;
using System.Collections;
public class ShotScript : MonoBehaviour
{
//public int damage = 2;
public GameObject shot;
public bool isEnemyShot = false;
void Start()
{
}
void OnCollisionEnter2D(Collision2D other){
if (other.gameObject.tag == "Enemy") {
DestroyObject(shot.gameObject);
}
}
}
On both objects I used a rigid body
Did you also put a collider on both ?
Answer by DoTA_KAMIKADzE · Apr 19, 2015 at 12:55 AM
1)If that script is a component of your shot then just:
Destroy(gameObject);
2)If it is not then:
Destroy(shot);
Now also make sure for both cases that your Enemy indeed have an "Enemy" tag. In order to make sure that line of code runs you can always do something like:
if (other.gameObject.tag == "Enemy")
{
Debug.Log("Found enemy");
}
Also if it is the case #2 make sure that your shot is actually your shot, something like:
if (other.gameObject.tag == "Enemy")
{
if (shot != null) Debug.Log(shot.name);
}
The script is a component of my shot. I made the changes as you suggested, but it doesn't seem to work.
If I am using RigidBody, should the collision be set to discreet or continuous?
Think of it like this:
Discrete - Slower/less detection checking + better performance.
Continuous - Higher/more detection checking + worse performance.
So unless your object moves really fast you should use discrete.
Now to the problem, have you checked with both Debug.Log examples I gave you? If so did the first one posted "Found enemy" and the second one posted your shot game object name(that was spawned)?
If his answer solved your problem. Thank him by choosing the question as answered.
One question. The code is my shotscript. In unity I have the prefab for my shot. I attached the script to the prefab as a component. Should I attach the prefab to the script component or is that not necessary? Also, the script is a component of my shot and I made the changes as you suggested but it still doesn't respond.
Your answer