How to clear cached images from sprite renderer

Here is an experiment. It:

  • reads all png images from given location as Texture2Ds & converts them to Sprites
  • displays them all in sequence as animation frames
  • deallocates everything
  • repeats

Note the square wave-like memory allocation graph it produced and let it be a proof this allocation/deallocation bussines works just fine.

rick-n-roll

// LetsRick.cs

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using IO = System.IO;
    public class LetsRick : MonoBehaviour
    {
    	[SerializeField] string _directoryPath = "D:/rick-n-roll/";
    	[SerializeField] float _delayBetweenFrames = 0.16f;
    	SpriteRenderer _spriteRenderer = null;
    	IEnumerator Start ()
    	{
    		_spriteRenderer = gameObject.AddComponent<SpriteRenderer>();
    		
    		var wait = new WaitForSeconds( 0.5f );
    		string[] files = IO.Directory.GetFiles( _directoryPath );
    		if( files.Length!=0 )
    		{
    			List<Sprite> frames = new List<Sprite>(128);
    			while( true )
    			{
    				// load all images as sprites, at once:
    				foreach( string filePath in files )
    				{
    					var bytes = IO.File.ReadAllBytes( filePath );
    					Texture2D texture = new Texture2D( 2 , 2 , TextureFormat.RGB24 , 0 , false );
    					if( ImageConversion.LoadImage( texture , bytes , true ) )
    					{
    						Sprite sprite = Sprite.Create( texture , new Rect(0,0,texture.width,texture.height) , new Vector2( 0.5f , 0.5f ) );
    						frames.Add( sprite );
    					}
    					else Debug.LogWarning($"image load failed, path: \"{filePath}\"");
    				}
    
    				// display all images in sequence:
    				var frameDuration = new WaitForSeconds( _delayBetweenFrames );
    				for( int i=0 ; i<frames.Count ; i++ )
    				{
    					_spriteRenderer.sprite = frames[i];
    					yield return frameDuration;
    				}
    
    				// free memory up:
    				for( int i=frames.Count-1 ; i!=-1 ; i-- )
    				{
    					Object.Destroy( frames[i].texture );
    					Object.Destroy( frames[i] );
    				}
    				frames.Clear();
    
    				// a lof of time to check it out in the profiler:
    				yield return wait;
    			}
    		}
    		else Debug.LogWarning($"no files found for path: \"{_directoryPath}\"");
    	}
    }