Search Unity

  1. Looking for a job or to hire someone for a project? Check out the re-opened job forums.
    Dismiss Notice
  2. Unity 2020 LTS & Unity 2021.1 have been released.
    Dismiss Notice
  3. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

Runtime Generated Textures Not Releasing Memory

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

  1. gretty


    Jun 20, 2012

    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 () {
    3.         if (Input.GetKeyDown(KeyCode.Space)) {
    4.             StartCoroutine( downloadFile(",151.219708834037&zoom=18&size=512x512&scale=1&maptype=satellite&format=png&sensor=true") );
    5.             guiTxt.text = "Downloading Texture";
    6.         }
    7.     }
    9.     IEnumerator downloadFile(string url) {
    11.         WWW www = new WWW(url);
    13.         while(!www.isDone)
    14.             yield return www;
    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.     }
    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
    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.     }