- Home /
How to load large texture and immediately release the memory of previous texture loaded
I'm trying to load a 2048 X 2048 texture every frame in Update(), before or after but not during any rendering, and also make sure that any memory from the previous loading of a texture is immediately released as the texture is large. Psuedocode:
Update function called
Load image into texture
Set texture. Force immediate release of memory used for the previous texture, and any temporary memory buffers allocated.
Update function exits
Note: I've tried forcing GC to no avail. And this is not for a game, but rather a special type of simulation so doing it every frame is what I want.
I've tried many different ways, but while I can load the texture the memory won't release and Unity crashes. Here's some code that I tried (also tried using WWW. Note: the same PNG file being loaded each time is just for test, later there will be thousands of different files):
/within Update()
txtr = new Texture2D(2048,2048);
FileStream fs = new FileStream("C:UsersUserPicturesMactexture.png", FileMode.Open, FileAccess.Read);
byte[] imageData = new byte[fs.Length];
fs.Read(imageData, 0, (int) fs.Length);
txtr.LoadImage(imageData);
renderer.material.mainTexture = txtr;
fs.Dispose();//doesn't help with memory not being released
System.GC.Collect();//doesn't help with memory not being released
System.GC.WaitForPendingFinalizers();//doesn't help with memory not being released
Answer by Jashengmato · Aug 18, 2014 at 01:16 AM
just do this after loading the new texture:
Resources.UnloadUnusedAssets();
System.GC.Collect();
And here are some other useful scripts: Click Me