- Home /
Need to manually destroy GameObject?
Should I destroy GameObject manually when it goes out of scope? (Since GameObject class must be a wrapper around native class, the answer - yes. But i'm not sure.) In this code GameObject is locally scoped.
void foo()
{
GameObject mGameObject = new GameObject("name");
// Destroy(mGameObject); => WE WON'T CALL THIS METHOD
}
We didn't call Destroy(mGameObject); => it will persist in memory (memory leak?) Should we always manually destroy locally scoped GameObjects (and similar objects then have Destroy() method) when they go out of scope?
Answer by Em3rgency · Jul 04, 2013 at 12:53 PM
No, you don't need to do this. And in this example (I miss remember the exact message) but it would tell you that you're trying to access something out of scope as an error.
EDIT: Ok, so for one thing, I doubt you can even "new" a game object. Shouldn't all game objects be instantiated? And if so, a game object will remain instantiated (and use up resources) until you manually destroy it. Here is an older question on a similar subject http://answers.unity3d.com/questions/209101/do-un-active-game-objects-still-use-memory.html
Now, if we're talking other classes that you allocate memory for with new, as far as I've checked, there is no "delete" to accompany the new like in c++, so I assume freeing up memory is done automatically. At least I sure as hell hope so.
Oh,I actually didn't mean this (it's my fault). By "Destroy(mGameObject);" I mean: was object already destroyed OR it wasn't destroyed? (actually became memory leak that will be persistent untill we unload the whole scene).
Actually, I'm not a programmer (I'm graphic designer who just learns game program$$anonymous$$g) but I found this: http://docs.unity3d.com/Documentation/ScriptReference/GameObject.GameObject.html
Look, the link you provided is about changing particular fields of objects. It's affect the following loop in Unity (must be implemented something like this):
//pseudocode
void update()
{
foreach(GameObject in list of Entities)
if(GameObject.active == true)
GameObject.update()
}
You're right w/ last statement: "normal" C# objects will be destroyed when go out of scope. But, you're right again, we talk about objects that wrap native classes. So, the destruction is trickier here and can depend on implementation done by Unity. I think your answer is complete enough to be checked as accepted!
Well the link is a discussion about memory conservation. Either by disabling the object or destroying it. As both cases were exa$$anonymous$$ed, I thought it was on subject :)
Your answer

Follow this Question
Related Questions
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
Why does my bullet prefab get destroyed? 1 Answer
Destroying Game Object On MouseButtonDown + Distance Collision 0 Answers
How to Play 3D Sound and Keep Script on Multiple Prefabs after Destroying a gameObject? 0 Answers
References to GameObject become null 1 Answer