Texture2D does not delete itself. Any new Texture2D objects you make must be processed with UnityEngine.Object.Destroy(texture2D) by the end of their lifespan or they will live in memory forever.
I thus was interested to build a class that will automatically destroy the Texture2D it contains when it goes out of scope.
ie.:
public class Texture2DManaged
{
public Texture2D texture2D;
public Texture2DManaged(int width, int height) {
texture2D = new Texture2D(width, height);
}
~Texture2DManaged() {
Debug.Log("DESTRUCTOR RUN");
UnityEngine.Object.Destroy(texture2D);
texture2D = null;
}
}
Then, in an Update() loop on any game object to test:
if (Input.GetMouseButtonDown(0)) {
Texture2DManaged texture = new Texture2DManaged(5000, 5000);
//UnityEngine.Object.Destroy(texture.texture2D);
}
This code as is runs the DESTRUCTOR RUN debug code, but yet memory use continually rises in the Profiler when you click. By contrast, if you enable the Destroy line in the Update on click loop, this memory rise stops.
Ie. The Destroy line works correctly on mouse click but not correctly in the destructor. Any thoughts or solutions?