- Home /
Destroy Gameobject on Collision not working?
I'm trying to destroy an object called "Spear" after it collides with the "ground". But it just keeps going?
using UnityEngine;
using System.Collections;
public class LauncherScript: MonoBehaviour {
void Update(){
transform.Translate(Vector3.right*30 * Time.deltaTime, Space.World);
}
void OnCollisionEnter(Collision other) {
if(other.collider.name == "ground")
{
Debug.Log("Collided");
Destroy(other.gameObject);
}
}
}
Is your debug log getting called? Or is the whole thing being ignored?
Answer by Razputin · Dec 11, 2014 at 12:19 AM
I didn't have a rigidbody on the spear. Plus the script was wrong.
I put
public class LauncherScript: MonoBehaviour {
void OnCollisionEnter(Collision other) {
if(other.collider.name == "Spear")
{
Debug.Log("Collided");
Destroy(other.gameObject);
}
}
}
on the ground and
public class SpearLauncher : MonoBehaviour {
void Update(){
transform.Translate(Vector3.right*30 * Time.deltaTime, Space.World);
}
}
on the spear
Answer by awplays49 · Dec 11, 2014 at 12:20 AM
You should be doing
if (col.GameObject.name == "Name Here")
{
Destroy (GameObject.find ("Other Name Here");
}
my bad. on line 3 do this. my apologies.
Destroy (col.GameObject.find ("Other Name Here");
This is horribly inefficient and unnecessary. He was doing it correctly. The issue was that he didn't have a rigidbody component.
well then.. guess youve never been wrong about anything
When did I say that? I was simply saying that your method is wrong. That doesn't mean that I'm right about everything. There's just no point in doing an unnecessary GameObject.Find call since it is a very heavy function.
Answer by Solokeh · Dec 11, 2014 at 01:00 AM
Try putting this in your "ground" object:
void OnCollisionEnter (Collision col)
{
if(col.gameObject.name == "spear")
{
Destroy(col.gameObject);
}
}
}