Search Unity

Does this code destroy the GameObject: Memory isn't Decreasing

Discussion in 'Scripting' started by gretty, Jan 14, 2014.

  1. gretty

    gretty

    Joined:
    Jun 20, 2012
    Posts:
    72
    Hello

    I am attempting to delete a GameObject that is just a Plane with a texture on it. I am deleting it because I want to free up the memory its using (the texture requires alot of memory). But I dont think that the Plane is being destroyed - certainly I am not seeing any stabilisation or reduction in my games memory usage. I think it might be because I still have a reference to the Plane somewhere and C# isn't releasing the memory.

    Do you think my code is successfully releasing all the memory? Can you suggest what I can do to ensure that the GameObject is destroyed?

    Code (csharp):
    1.  
    2. public class TerrainManager : MonoBehaviour
    3. {
    4.     protected Dictionary<LatLonCoordinate, TerrainManagerNs.Plane> planes   = new Dictionary<LatLonCoordinate, TerrainManagerNs.Plane>();
    5.  
    6.     protected void clearTerrain() {
    7.         StopAllCoroutines();
    8.        
    9.         foreach (TerrainManagerNs.Plane plane in planes.Values) {
    10.             Debugger.print ("Deleting plane");
    11.             Destroy(plane);
    12.         }
    13.        
    14.         // Knowtice that the dictionary planes still refers to each Plane at this point in code
    15.         // So did the destroy above work even though planes still referred to the planes?
    16.         planes.Clear ();
    17.         //System.GC.Collect();
    18.     }
    19. }
    20.  
    21. public class Plane : MonoBehaviour
    22. {
    23.     void OnDestroy() {
    24.         Debugger.print ("Plane");
    25.         destroy ();
    26.     }
    27.    
    28.     private virtual void destroy() {
    29.         StopAllCoroutines();
    30.         Debug.Log ("Plane::Destroy()");
    31.         Destroy(this.gameObject.rigidbody);
    32.         Destroy(this.gameObject.collider);
    33.         Destroy(this.gameObject);
    34.         Destroy(this);
    35.     }
    36. }
     
  2. Sildaekar

    Sildaekar

    Joined:
    Jul 8, 2013
    Posts:
    95
    I'm not quite sure what is going on here, but have a look at this question on Unity Answers about Garbage Collection, also be sure that you understand how garbage collection in mono works as manually collecting the garbage is usually a bad idea, and just like in your own home it's best to let someone else take care of it. ;)
     
  3. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Destroy does destroy objects, but Unity objects are not part of Mono and are not garbage collected. You can use Resources.UnloadUnusedAssets.

    --Eric