- Home /
How to unload only 1 texture without a performance overhead?
Hi, I'm making a iphone rpg and finally came to meet memory doom and need to figure out a way to load and unload textures dynamically. The problem is I couldn't find a way to unload textures without stopping the game briefly and it does not look good at all.
I load texture of one item like below.
function GetIcon(g : Manager) : Texture2D
{ // generate instance if doesn't exist
if(g.balance.itemInst[id] == null){
// generate instance and set icon2D there
var clone : Item = Instantiate(this, Vector3.zero, Quaternion.identity).GetComponent(Item);
clone.icon2D = Resources.Load("Item Icon/" + class_ + '/' + gameObject.name, Texture2D);
g.balance.itemInst[id] = clone; // set item instance
clone.transform.parent = g.itemHolder; // group up
}
return g.balance.itemInst[id].icon2D; // from now on returns from instance
}
I googled around and my only option seems to be Resources.UnloadUnusedAssets().
I tried Destroy(ItemGameObject) which holds the only referece to Texture2D and GC did not collect it (Some post says losing reference to texture will unload it and some post says GC does not handle textures which is confusing to newbie like me)
I experimented myself with really big texture so that I can clearly see if it is being loaded and unloaded and Resources.UnloadUnusedAssets() only worked.
It'd be much appreciated if experienced Unity programmer could help me on this one.
Answer by Kryptos · Apr 10, 2012 at 12:01 PM
To allow GC to release the memory, destroying the GameObject with Destroy(gameObject)
may not be sufficent. You also need to release any reference to the resource.
For example, if you have a script with:
public Texture2D myTexture;
The best way to do that is to use the OnDestroy()
method:
void OnDestroy()
{
this.myTexture = null;
}
Resources.UnloadUnusedAssets()
only release resources loaded with Resources.Load()
.
You can call GC explicitly with:
System.GC.Collect();