- Home /
Cannot destroy objects
I am creating a new game object as follows:
rangeObject = new GameObject();
rangeObject.name = Time.frameCount + "";
Further along in my code I am destroying the object as a result of an event:
public void destroy()
{
Debug.Log("destroying range");
UnityEngine.Object.DestroyImmediate(rangeObject);
}
After the method above gets called I am still seeing the object in the object hierarchy. The reference to rangeObject hasn't changed in between the create/destroy and I made sure that the destroy line is being called (the log is working as intended). Note that I disable all the components in rangeObject elsewhere before the destroy gets called.
In the object hierarchy the range object named with the frame it was created on is still there and I can reactivate it's components which then work as if nothing was destroyed.
Is there a problem with what I am doing above?
I'm not certain but perhaps try using Destroy() rather than DestroyImmediate(), DestroyImmediate is usually only used in editor scripts where they can't be delayed to the end of a 'frame' as there isn't a frame. Also it shouldn't be necessary to have UnityEngine.Object but obviously that is just choice in coding convention.
Be very careful with calling DestroyImmediate(). It can also be used to destroy assets permanently. Is designed to only be used in the editor class.
Use Destroy() ins$$anonymous$$d.
Oh sorry, it was originally just UnityEngine.Object.Destroy I tried DestroyImmediate to see if it made any difference (it didn't). I am calling this from outside a monoBehaviour which is why I am using the fully qualified name to call it.
Okay, outside of monoBehaviour. That's a significant point, might want to add that to your question.
$$anonymous$$aybe you should be creating the GameObject using instantiate ins$$anonymous$$d of new. Working from memory here but I'm pretty sure Unity throws a fit if you try use the new keyword to create a GameObject inside a monoBehaviour.
No, it won't throw an error for new GameObject
, see the documentation. Are you sure you're destroying the correct object? Can you check whether all the references to the object are nullified after it is destroyed?
Your answer
![](https://koobas.hobune.stream/wayback/20220613145046im_/https://answers.unity.com/themes/thub/images/avi.jpg)