Search code examples
unity-game-engineramunity-ui

How to change a sprite (ui.image.sprite) and delete the previous one from RAM


I need to take a screenshot of the screen and put it as a sprite in the image component. I do it with this code:

public Texture2D TakeScreenshot()
{
Texture2D texture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGBA32, false);
texture.ReadPixels(new Rect(0,0, Screen.width, Screen.height), 0, 0);
texture.Apply();
return texture;
}
screenShot = screenshotHandler.TakeScreenshot();
image.sprite = Sprite.Create(screenShot, new Rect(0, 0, Screen.width, Screen.height), Vector2.zero);

The entire screen is filled with multi-colored random pixels, so the screenshot weighs about 15MB. I need to do this code multiple times and I noticed with the memory profiler that the previous screenshots are not removed from RAM. As a result, I have one final screenshot, and many screenshots in RAM that I don't need. What do I need to do to remove them?

RAM is extremely important in an game Untitled files are screenshots. I took more and less screenshots, I know for sure that they are screenshots

I tried using image.overrideSprite instead of image.sprite but screenshots stay in memory too


Solution

  • I solved the problem. I realized that the profiler says "Texture2D", but I thought about the sprite. Now my code looks like this:

    Destroy(screenShot);
    screenShot = screenshotHandler.TakeScreenshot();
    image.sprite = Sprite.Create(screenShot, new Rect(0, 0, Screen.width, Screen.height), Vector2.zero);
    

    Sorry for the stupid question