How to recover unused allocated memory?

So, much to my surprise, when I change the sprite on an Image component, it allocates more memory for it, even if I swap the sprite 10 times, it re-allocates more and more memory, and if you keep changing it hundreds of times, it eventually crashes. Even if you only have one image component, it ends up allocating memory for it a hundred times over.

Now, this is problematic, because I’m working on some projects where I will need to be swapping and changing sprites quite frequently, and “May come with a small case of ‘crashes every 20 minutes’” doesn’t look good on a product.

is there a way for me to reclaim some of that wasted memory? or is there a work around that is practical for this problem?

with some digging and testing, I found that you can use Resources.UnloadUnusedAssets(); to give garbage collection a helping hand. I also found that setting sprites to null before changing them helped.

the problem seems to be more serious than I realised. Watching the profiler, it seems that every time you change a sprite on a Image component, it creates new materials. So unloading them with Resources.UnloadUnusedAssets(); every minute or so helped a lot.