destroy object other objects instantiated from, returns missingReferenceException

hi. i want to instantiate an object and then after for example 3 seconds destroy it. therefore in its script I put “destroy(gameobject)”. but when it destroys i got an error and then no new object instantiates. because the main object destroyed!
how can i fix this problem ?

Hello there,

I think you may be a little confused about the way Instantiate() works. Let’s review:

As you can see on this page, the first argument you give an Instantiate() call is the “Prefab”. This prefab is a Template, and doesn’t actually get placed in the scene. Rather, it makes a COPY of that template and puts it in the scene.

In your case, if you want to destroy the copy (rather than the original), you would need to keep a reference to it.

Instead of using

Instantiate(objectClone, new Vector3(-7, -1, -1), Quaternion.identity);

You would use

GameObject theCopy = Instantiate(objectClone, new Vector3(-7, -1, -1), Quaternion.identity);

Then, to destroy that copy after three seconds, you just need to call Destroy(theCopy, 3.0f);.

Note that in your code above, you are doing Destroy(gameObject);. By itself, “gameObject” refers to the GameObject your script is attached to. That means that your code effectively deletes itself.

Another thing you could do is put a script on the prefab, so it deletes itself after three seconds.
In that case, you would just need to give it a Start() function with a Destroy(gameObject, 3.0f); line inside.

Oh, and to create a prefab you can simply drag an object from the scene to your assets folder.


I hope that helps!

Cheers,

~LegendBacon

Hi put the Instantiated object in a variable, then start a coroutine and use WaitForSeconds to wait 3 sec and then destroy the instantiated object.

    void Update()
    {
        if (...)
        {
             GameObject ObjectClone = Instantiate(YourGameObject);
             StartCoroutine(DestroyWithDelay(ObjectClone));
        }
    }

    IEnumerator DestroyWithDelay(GameObject ObjectClone)
    {
        yield return new WaitForSeconds(3);
        Destroy(ObjectClone);
    }