Monday 21 December 2015

Avoid memory leak in Unity3D when loading images

Recently I tried to make a picture player with Unity3D, should be easy... but is not...
It seems that Unity3D still has some problems regarding the memory leaks when accessing resources from local disk. I tried to use the basic way something like this:

var _texture2D = new Texture2D(1024, 1024, TextureFormat.RGBA4444, false);//this is initialised only once
void ShowPicture(string filePath)
{
byte[] fileData = File.ReadAllBytes(filePath);
_texture2D.LoadImage(fileData);
Sprite sprite = Sprite.Create(_texture2D, new Rect(0, 0, _texture2D.width, _texture2D.height), Vector2.zero);              
myImage.GetComponent<Image>().sprite = sprite;
}
Ok, this seems right, but it's not, because after a while the application crashes.
I tried to call GC.Collect(), but still the same result.
After a lot of attempts, the solution is to pass directly the texture:

    private IEnumerator LoadPicture(string file)
    {
        WWW www = new WWW("file://" + file);
        yield return www;
        www.LoadImageIntoTexture(_texture2D);
        myImage.GetComponent<CanvasRenderer>().SetTexture(_texture2D);
    }

The issue here is that the aspect ratio is not correct.



2 comments:

  1. You saved my life :) ! I've been searching all the internet for so long... Thank you so much !

    ReplyDelete
  2. It works perfectly! Thank you so much!

    ReplyDelete