Desttroy instantiate rigidbody

Hi Everybody !

I have a problem, I can’t destroy entire object with this code ( only rigidbody ) :

using UnityEngine;
using System.Collections;

public class instantiate : MonoBehaviour
{
    public Rigidbody rocketPrefab;
    public Transform barrelEnd;
  
    void Update ()
    {
        if(Input.GetButtonDown("Fire1"))
        {
            int i;
            for (i=0;i<=10;i++){
            Rigidbody rocketInstance;
            rocketInstance = Instantiate(rocketPrefab, barrelEnd.position, barrelEnd.rotation) as Rigidbody;
            rocketInstance.AddForce(barrelEnd.forward * 2);
            rocketInstance.AddForce(barrelEnd.right * 1);
                Destroy (rocketInstance, 5);

            }
        }
    }
}

After 5 seconds, the balls ( rockets is sphere in scene ) don’t disapear and when I replace rigidbody by object I have error. What can I do ? I want destroy entire object et not only Rigidbody.

Hey there :slight_smile:
A quick glance it looks like your requesting for the rBody to be destroyed and not it’s gameobject in which you wish to destory. Your code is actually working correctly but with a slight logic issue, a simple solution though, try this :

using UnityEngine;
using System.Collections;

public class testMe : MonoBehaviour{ //Change your class name back.
    public Rigidbody rocketPrefab;
    public Transform barrelEnd;
 
    void Update (){
        if(Input.GetButtonDown("Fire1")){
            //TODO:You don't need this :
            /*
            int i;
            for (i=0;i<=10;i++){
            */

            //Though there's nothing wrong with it, and
            //possibly could be useful if you needed to change it for any reason down the road.
            //I don't think you would though, not without causing headache elsewhere.

            //This is less code, and perhaps a nicer format?

            for(int i=0;i<10;i++){
                Rigidbody rocketInstance;
                rocketInstance = Instantiate(rocketPrefab, barrelEnd.position, barrelEnd.rotation) as Rigidbody;
                rocketInstance.AddForce(barrelEnd.forward * 2f); //Don't forget to use your f!
                rocketInstance.AddForce(barrelEnd.right * 1f); //Why multiplying by 1?, additionally, don't forget your 'F'!
                Destroy (rocketInstance.gameObject); //You destroy the game object to rid yourself of the object, if you destory the rBody, you only remove it from said object.
            }
        }
    }
}
1 Like

Thank you very much, that’s work perfectly. I will follow your optimisation for less code. Have a nice day !

1 Like