Im using UnityWebRequest to load an image.
This is the code.
UnityWebRequest uwr;
StartCoroutine(LoadImageCorroutine());
IEnumerator LoadImageCorroutine()
{
using (uwr = UnityWebRequestTexture.GetTexture(@"file:///C://UnityTests/Filerepository/Items/3faju5ozafrz.png"))
{
yield return uwr.SendWebRequest();
rawImage.texture = DownloadHandlerTexture.GetContent(uwr);
//Debug.Log(i.ToString());
}
uwr.Dispose();
StopCoroutine(LoadImageCorroutine());
}
I ran some performance test and noted that the Memory usage where going up and up each time I called the coroutine and didnt go down afterwards.
Considering the CPU load going down with time, it seems the coroutine either properly stopping or at least going idle.
How do I get rid of whatever UnityWebRequest is loading into my Memory?
Myself already ran into this issue once before. You can see what happens by using the profiler (CTRL + 7) and do a memory snapshot
before and after running your routine.
SPOILER: You will see that after every run of your download routine there is one more texture asset in the memory which is never destroyed.
The thing is that any Texture
downloaded via UnityWebRequestTexture.GetTexture
is not GC collected even if it is nowhere referenced anymore! So each run of the coroutine adds one more texture instance to your memory.
In order to solve this once you know you actually want to destroy the texture you'll have to do so "manually":
IEnumerator LoadImageCorroutine()
{
using (var uwr = UnityWebRequestTexture.GetTexture(@"file:///C://UnityTests/Filerepository/Items/3faju5ozafrz.png"))
{
yield return uwr.SendWebRequest();
// I would always check for errors first
if(uwr.isHttpError || uwr.isNetworkError)
{
Debug.LogError($"Could not load texture do to {uwr.responseCode} - \"{uwr.error}\"", this);
yield break;
}
// Destroy the current texture instance
if(rawImage.texture)
{
Destroy(rawImage.texture);
}
rawImage.texture = DownloadHandlerTexture.GetContent(uwr);
//Debug.Log(i.ToString());
}
// since you are using "using" there is no need to call Dispose() manually
// This is anyway the end of your coroutine .. you do not want to call
// StopCoroutine(LoadImageCorroutine()) here
}