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?