Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Increasing memory usage when using target texture and saving the image

Discussion in 'Scripting' started by newerish, Apr 20, 2020.

  1. newerish

    newerish

    Joined:
    Sep 13, 2019
    Posts:
    11
    Hi,

    The code below is run many times during every mainCamera's Update(). storeCamera is not the same as mainCamera and has no script component. The problem is that Unity's memory consumption becomes absurdly high after running this (going from 2GB to 11GB in 15sec). Is this issue related to Unity or the code?

    Code (CSharp):
    1.  
    2. void Store(){
    3. ...
    4. storeCamera.Render();
    5. ...
    6. RenderTexture.active = storeCamera.targetTexture;
    7. Texture2D r = new Texture2D(storeCamera.targetTexture.width, storeCamera.targetTexture.height);
    8. r.ReadPixels(new Rect(0, 0, storeCamera.targetTexture.width, storeCamera.targetTexture.height), 0, 0);
    9. r.Apply();
    10. byte[] bytes = r.EncodeToJPG(75);
    11. File.WriteAllBytes(framePath + frameIndex + ".jpg", bytes);
    12. frameIndex++;    
    13. }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,971
    When you make a Texture2D() yourself you have to Destroy() it when you're done, otherwise it will continue to occupy memory.
     
  3. newerish

    newerish

    Joined:
    Sep 13, 2019
    Posts:
    11
    Thank you.
     
    Kurt-Dekker likes this.