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);
Sprite sprite = Sprite.Create(_texture2D, new Rect(0, 0, _texture2D.width, _texture2D.height),;              
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;

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