- Home /
How can I make this object destroy on Collison?
So I'm trying to make a object disappear when it collides with my bullet, a capsule with a rigidbody and capsule collider, but I only want objects with the tag Destructable to disappear. My code so far is below please any help would be much appreciated.
using UnityEngine; using System.Collections;
public class bulletScript : MonoBehaviour
{
public float bulletSpeed;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
}
//Called everytime there is a pyshics update
void FixedUpdate()
{
rigidbody.AddForce (Vector3.forward * bulletSpeed);
}
void OnCollisionEnter( Collision col)
{
if (col.gameObject.tag == "Destructable")
{
Destroy(gameObject);
}
}
}
I figured it out I set the wrong object to Destructable
Answer by AnXgotta · Feb 19, 2014 at 03:05 PM
Edit: I just saw your edit at the bottom saying you figured it out... oh well.
Well, your code looks ok except for one thing.
You say you want to destroy the object that the bullet hits?
Look at you OnCollisionEnter(...)
function. Destroy(gameObject)
will destroy the object that this script is attached to.
So, we need to get the gameObject
of the thing we collided with... the Collision col
parameter helps us do this. See below.
void OnCollisionEnter( Collision col)
{
if (col.gameObject.tag == "Destructable")
{
Destroy(col.gameObject); // THIS WILL DESTROY THE OBJECT WE COLLIDED
Destroy(gameObject); // THIS WILL DESTROY THE BULLET
}
}