- Home /
How do I destroy a gun bullet clone?
Hey everyone! I know for a fact this question has been asked before; however, the other forum pages I looked at didn't have the answer I was looking for so here goes!
Just like the topic, I've got a perfectly fine gun script that shoots without any problems. Unfortunately, I'm still pretty new to scripting and Unity and I've been having problems understanding why my bullet clone isn't being destroyed.
using UnityEngine; using System.Collections;
public class Shoot : MonoBehaviour {
public Rigidbody rocket;
public Rigidbody n_rocket;
public float speed = 10f;
public float destroySpeed = .5f;
void FireRocket ()
{
Rigidbody n_rocket = (Rigidbody)Instantiate(rocket, transform.position, transform.rotation);
n_rocket.velocity = transform.forward * speed;
}
void Update ()
{
if (Input.GetButtonDown("Fire1"))
{
FireRocket();
}
Destroy(n_rocket, destroySpeed);
}
}
Now it works perfectly fine if I write the Destroy script like so:
Destroy (GameObject.Find("Bullet (Clone)"), destroySpeed);
however, from what I've seen written on the forums, using GameObject.Find can be inefficient for something like this. So why does the GameObject.Find work but it doesn't destroy the object if I reference it by it's name, n_rocket?
Is FireRocket(); called constantly? If so, you should implement some kind of pooling system, Instantiating gameobjects can be resource intensive depending how you implement it. Otherwise you can do like Cherno's answer.
Answer by Cherno · Nov 22, 2015 at 11:39 AM
You declare a reference to the instantiated rigidbody called "n_rocket". Later, you use the Destroy function to destroy the referenced object, which is still a rigidbody, so only the rigidbody component of the gameobject is destroyed, not the whole GameObject.
The solution is of course to not instantiate a rigidbody, but rather a whole GameObject (which has a rigidbody you can access via GetComponent), and destroy this instead.
Edit: Or do it like this:
Destroy(n_rocket.gameObject, destroySpeed);
Answer by MewEight · Nov 23, 2015 at 03:50 AM
My personal method would be just to use a coroutine.
void FireRocket ()
{
Rigidbody n_rocket = (Rigidbody)Instantiate(rocket, transform.position, transform.rotation);
n_rocket.velocity = transform.forward * speed;
StartCoroutine(DestroyLater(n_rocket.gameObject, destroySpeed);
}
private IEnumerator DestroyLater(GameObject obj, float delay)
{
yield return new WaitForSeconds(delay);
Destroy(obj);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612045940im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Make make gameObject invisible until collision with bullet 1 Answer
Destroying an object from its script. 1 Answer
Trouble with destroy function 2 Answers