Cannot Instantiate a destroyed object

Hi,
I have a game where you have a tank and right now there a 2 turrets that look at the player and instantiate a Projectile prefab in a random number of seconds. The problem is when i try to destroy the projectile after collision the turrets can no longer shoot. It also gives me the error “The object of type ‘Rigidbody’ has been destroyed but you are still trying to access it.”

My TurretShoot Script

    public Rigidbody clone;
    public float speed;
    public int minTime;
    public int maxTime;





    // Use this for initialization
    void Start () 
    {
        StartCoroutine("WaitAndShoot");
   
    }
   
    // Update is called once per frame
    void Update () 
    {

    }

    IEnumerator WaitAndShoot()
    {
        // suspend execution for 5 seconds
        while (true) 
        {
            yield return new WaitForSeconds (Random.Range(minTime, maxTime));
            clone = Instantiate (clone, transform.position, transform.rotation) as Rigidbody;
            clone.AddForce (transform.forward * speed);
        }

    }
}

My Destroy projectile script

    // Use this for initialization
    void Start () 
    {
   
    }
   
    // Update is called once per frame
    void Update () 
    {
   
    }

    void OnCollisionEnter(Collision collision) {
        Destroy (gameObject);
    }
}

Could be that you have assigned your projectile from Scene window?
Assign the reference from Project window instead.

I had assigned it from the project window and just retried to make sure and it did the same thing.

In your WaitAndShoot() method:

clone = Instantiate (clone, transform.position, transform.rotation) as Rigidbody;

You are instantiating and setting a clone of the clone. Try one of these methods:

Rigidbody newClone = (Rigidbody)Instantiate (clone, transform.position, transform.rotation);
newClone.AddForce(transform.forward * speed);

or just

(Rigidbody)Instantiate (clone, transform.position, transform.rotation).AddForce(transform.forward * speed)

I couldnt get either of these to work. The first one gave me the same result and the second one it wasnt showing it was correct in monodevelop. Thank you tho.

Ok sorry, I was trying to take a shortcut without checking it first :eyes:

Just try this again. Cut and paste.

Rigidbody projectile = Instantiate(clone, transform.position, transform.rotation) as Rigidbody;
projectile.AddForce(transform.forward * speed);

Otherwise maybe try placing the yield return line in your WaitAndShoot function after the Instantiate and addforce calls. See if that helps.

1 Like

Thanks porters! That worked. Ive been trying to figure this out for 2 days. Thanks again man!!

No worries mate. What worked? The code above, or moving the yield return line in your WaitAndShoot function?