I can't destroy the object

I have a player and in the hierarchy of this player I created a 3d sphere. I added a script called Instantiate Around Player:

 void ActDestroy()
 {
     if (setTime <= 0)
     {
         Destroy(cubePrefab);
     }
 }
 void OnGUI()
 {
     if (GUI.Button(new Rect(20, Screen.height * 0.66f, 200, 30), "Generate Elements"))
     {
         CreateElements();
     }
 }

It creates cube when OnGUI() is clicked. But after some certain seconds pass, it does not destroy the cube.

Thank you.

Hi,

First, you need to make sure that the Destroy function is being called; I suggest you to start debugging if you’re not : “Unity - Manual : Debug C# code in Unity” or, as I think everyone do, using Debug.Log(). You need to be sure that your code (like the setTime variable) is not responsible for other features to not work. (Destroy)
Then, if you have trouble with the Destroy, make sure you’re calling the Destroy function on a GameObject Object if you want to destroy the entire game object : as you can see here (Unity - Scripting API: Object.Destroy), calling it from a script instance will simply remove the script instance from the game object. So, if cubePrefab is not storing a GameObject reference :

    Destroy(cubePrefab.gameObject);

You also need to make sure that cubePrefab is the instance that you’re trying to destroy, and not the base object that you’re cloning. If you’re spawning cubes doing :

    Instantiate(cubePrefab, ...);

Then you won’t be deleting the instance of the cubePrefab. You need to store it somewhere, to destroy it later :

GameObject cubeInstance;
void A() 
{
    cubeInstance = Instantiate(cubePrefab, /* transform location */);
}
void B()
{ 
   Destroy(cubeInstance);
}

Hope this helps !

1 Like

^ ^ ^ You can NEVER destroy a prefab this way. You’re probably even getting a warning in your console log.

Instancing and prefabs in Unity and naming your variables:

If you name your public / serialized fields (variables) as simply “thing” then you set yourself up for confusion.

If something is a prefab, name it that, such as public GameObject ThingPrefab; and only drag prefabs into it. Prefabs are “dead things (assets on disk) waiting to be Instantiated.”

If something is already in the scene or you Instantiate<T>(); it in code, then store the result in a properly-named variable such as private GameObject ThingInstance;

Naming is hard… name things WELL to reduce your own confusion and wasted time.

2 Likes

I finally understood the concept :blush:

Thank you all for making me understanding the conceptual state of this Destroy(gameObject)

1 Like