UnityWebRequest Memory Leak

I ran into memory leak issue when using UnityWebRequest to download texture. I have narrowed down the issue to the following code:

public class WebTest : MonoBehaviour
{
    public string url;
    public void DownloadImage()
    {
        StartCoroutine(ImageCoroutine());
    }
    IEnumerator ImageCoroutine()
    {
        using UnityWebRequest imageDownload = UnityWebRequestTexture.GetTexture(url);

        yield return imageDownload.SendWebRequest();
    }
}

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.

Hello! It’s pretty weird to download a texture and not use it :slight_smile: 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

Yes, it creates a texture at the end of the download.

1 Like

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?

As I understand, anything that you create on the fly that inherits from UnityEngine.Object, you will need to clean up yourself.

Had the same problem with UnityWebRequest called in Coroutine, thanks for your replies mates!