x


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.

more ▼

asked Apr 10 '12 at 10:17 AM

proteinbeer gravatar image

proteinbeer
26 3 3 8

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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();
more ▼

answered Apr 10 '12 at 12:01 PM

Kryptos gravatar image

Kryptos
7.2k 5 32

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x2190
x326
x20
x17
x12

asked: Apr 10 '12 at 10:17 AM

Seen: 1162 times

Last Updated: May 09 '12 at 01:34 AM