cleanup allocated memory for texture2D

I’m wondering if you create a new Texture2D and fill it up with something and then later recreate them and fill them up again, how do you release the memory allocated the previous time? So if for example you want to keep the same name but recreate the texture with new dimensions. I’m writing a rather lengthy routine but this is a problem i have, as my application eventually crashes. If i create the Texture2D only once this problem doesn’t occur. So i can only conclude that if you construct a new Texture2D… memory is allocated at some point but if you then construct it again with other dimensions somehow there’s a need to cleanup the memory previously allocated but i don’t see a clear way to do this.

Does this make any sense, and if so what can be done about it?

It depends on the OS as well. I usually clear asset myself after I end using it. Or you can reuse one Texture2D every time.

For example:

BAD:

for(int i=0;i<10;i++){
    Texture2D texture = new Texture2D(256,256);
}

GOOD:

Texture2D texture = new Texture2D(256,256);
for(int i=0;i<10;i++){
    texture = new Texture2D(256,256);
}

Or you can set texture = null; to clean up, but you will have to use UnloadUnusedAssets() and System.GC.Collect() at some point if you create a lot of them.

Yes thats exactly what i ended up doing, your second example and setting texture to null and then use UnloadUnusedAssets() and System.GC.Collect().

So this actually solved my problem in the Unity editor and it also helped slightly when i made an iOS build and tested on my ipad, but even then after a couple of additional loops on the ipad it would eventually crash. I have no idea why, if the texture is created only once its all working fine. So reconstructing it must be what is causing it to crash