Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Runtime Generated Textures Not Releasing Memory

Discussion in 'Scripting' started by gretty, Dec 18, 2013.

  1. gretty

    gretty

    Joined:
    Jun 20, 2012
    Posts:
    72
    Hello

    My textures that I download at runtime are not releasing memory when I destroy them. Can you tell me what is going wrong and how I can release the texture (.png) memory?

    I have an example scene and 1 script that very nicely simply demonstrates the problem. When the user presses the space bar, we download a texture (satellite image) and apply it to a cube (we delete the cubes existing texture to release that memory).

    I am profiling my .exe using the task manager and it shows that whenever I press space bar that the memory always increases (by about 1mb) and doesn't decrease or stay constant. So the texture memory isn't being released.

    Any advice on how I can release the textures memory or achieve any memory savings?

    My script and scene can be downloaded here:

    Script Scene

    Simple Script:

    Code (csharp):
    1. void Update () {
    2.        
    3.         if (Input.GetKeyDown(KeyCode.Space)) {
    4.             StartCoroutine( downloadFile("http://maps.google.com/maps/api/staticmap?center=-33.7600944982221,151.219708834037&zoom=18&size=512x512&scale=1&maptype=satellite&format=png&sensor=true") );
    5.             guiTxt.text = "Downloading Texture";
    6.         }
    7.     }
    8.    
    9.     IEnumerator downloadFile(string url) {
    10.        
    11.         WWW www = new WWW(url);
    12.                
    13.         while(!www.isDone)
    14.             yield return www;
    15.        
    16.         if (www.isDone) {
    17.             DestroyImmediate(GameObject.Find ("Cube").renderer.material.mainTexture, true);
    18.             System.GC.Collect();
    19.             Resources.UnloadUnusedAssets();
    20.             GameObject.Find ("Cube").renderer.material.mainTexture = compressTexture(www);  //www.texture;
    21.             guiTxt.text = "New Texture Applied";
    22.         }
    23.     }
    24.    
    25.     Texture compressTexture(WWW www) {
    26.         // Post: My method to compress textures that are currently used/displayed in game
    27.         //       Without this code the texture uses 1.1 megabytes!!! With it, it uses about 300k
    28.        
    29.         Texture2D texture = new Texture2D(2, 2, TextureFormat.RGB24, false); // size params can be anything AFAIK
    30.         www.LoadImageIntoTexture(texture);
    31.         texture.Apply(false, false);
    32.         texture.Compress(true);
    33.         return texture;
    34.     }

    [2]: