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. Dismiss Notice

Bug UnityWebRequest Memory Leak

Discussion in 'Scripting' started by xuliming1994, Jan 19, 2022.

  1. xuliming1994

    xuliming1994

    Joined:
    May 13, 2021
    Posts:
    44
    I ran into memory leak issue when using UnityWebRequest to download texture. I have narrowed down the issue to the following code:

    Code (CSharp):
    1. public class WebTest : MonoBehaviour
    2. {
    3.     public string url;
    4.     public void DownloadImage()
    5.     {
    6.         StartCoroutine(ImageCoroutine());
    7.     }
    8.     IEnumerator ImageCoroutine()
    9.     {
    10.         using UnityWebRequest imageDownload = UnityWebRequestTexture.GetTexture(url);
    11.  
    12.         yield return imageDownload.SendWebRequest();
    13.     }
    14. }
    15.  
    I didn't do anything with the texture, this is to demonstrate the memory leak.

    I put the script in a new urp project and call DownloadImage from a button. The memory increases with every click and based on profiler the texture is stored in Not Saved/Texture2D. It persists in editor play mode, development build and shipped build.

    The code is almost a copy-paste from the official doc for UnityWebRequestTexture.GetTexture by the way.
     
  2. ByMedion

    ByMedion

    Joined:
    May 10, 2018
    Posts:
    19
    Hello! It's pretty weird to download a texture and not use it :) Texture2D is an unmanaged resource and you need to call Destroy(tex) yourself to free the memory.

    Perhaps the webrequest creates this Texture2D after downloading immediately, not only when you actually use it
     
  3. Aurimas-Cernius

    Aurimas-Cernius

    Unity Technologies

    Joined:
    Jul 31, 2013
    Posts:
    3,637
    Yes, it creates a texture at the end of the download.
     
    ByMedion likes this.
  4. xuliming1994

    xuliming1994

    Joined:
    May 13, 2021
    Posts:
    44
    I had assumed that C# collects all object that has no reference to. I don't see the docs on GetTexture or Texture2D saying I need to destroy it to release the memory. Is there any guide on how to manage Texture2D?
     
  5. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,848
    As I understand, anything that you create on the fly that inherits from UnityEngine.Object, you will need to clean up yourself.
     
  6. Babster

    Babster

    Joined:
    Jun 7, 2020
    Posts:
    20
    Had the same problem with UnityWebRequest called in Coroutine, thanks for your replies mates!