How do you free a manually created texture?

This is probably trivial, but I’m loading a very very large texture like this:

  // Load huge tga map as an image.
  var i = new nImage();
  i.Load("map.tga");

  // Create texture from subsection of image
  Texture t = i.Texture(640, 640, 1200, 1200);

Afterwards I want to dispose of the texture I’ve created. Normally if I loaded a texture using Resources.Load() I’d use Resources.UnloadAsset() to dispose of it.

However, this texture is created using (internally to nImage):

    public Texture2D Texture (int x, int y, int width, int height)
    {
      var bytes = Section (x, y, width, height);
      if (bytes == null)
        return null;
      var texture = new Texture2D(width, height, TextureFormat.ARGB32, true, true);
      texture.SetPixels32(bytes, 0);
      texture.Apply();
      return texture;
    }

How do I force the texture to be removed from the graphics memory of the card?

(It doesn’t appear to be automatic, because I’m hitting memory exhaustion errors on the graphics card after a while).

You dont free anything manually in C#. Memory is managed by mechanism called Garbage Collector, it releases memory at its own time, you can however make a request for garbage collector to start collecting unused memory by calling GC.Collect(); But be aware it doesnt clean up memory, only informs garbage collector that you want him to collect mem. You can also use GC.WaitForPendingFinalizers() method, that will perform similiar to GC.Collect(), but also it will freeze your application untill cleanup is performed, so its most like direct cleanup method, but not exactly, also keep on mind that calling WaitForPendingFinalizers(), especially while game is running, is rather bad idea, since it can freeze your app badly.

You can read more about it here Unity - Manual: Memory in Unity

About Resources.UnloadAssets() - i dont know what does it exatly do but i assume it closes opened IO resources, like file descriptors, rather then really free memory (however its releated).

Ryba’s answer applies to allocations of objects in code, but not resources like Textures.

You have to manually unload a texture you have created using Resources.UnloadAsset(myTexture).

http://forum.unity3d.com/threads/resources-unloadasset-unloads-texture-but-doesnt-reload-when-its-needed-again.165161/

I just stumbled upon this problem when working on my dual quaternion skinning script.

I use textures to pass data to GPU for calculations and retrieve results.

After optimizing everything else the biggest bottleneck is GC.Collect() when using GetPixels (code below)

https://bitbucket.org/MadC9ke/unity3d-dual-quaternion-skinning/src/a6ea850456861672faae59848e32dee1903decec/Code/DQ%20animator/MadCakeMeshAnimator.cs?at=master&fileviewer=file-view-default#MadCakeMeshAnimator.cs-192

I think you need to call Destroy on the manually created texture.

E.g. see Issue with Texture2D memory leak in Unity