Memory issues when taking Screenshots ?

Hello Guys i am having memory issues when we create a screenshot in unity, encode the given texture to bytes and clear the texture from memory . I found and used this code for shrinking the texture size (http://wiki.unity3d.com/index.php/TextureScale) and it’s worked well but it seems like whenever we create a screenshot in memory the textures are never cleared from resources or memory .I am using the following code , to take and store the screen shot as bytes, and then upon saving, saving the raw byte data to the system file .

IEnumerator takeScreenshot(){

	//*** if byte array already has values  null it out
	if(screenGrabBytes != null ){

		screenGrabBytes = null;

		screenGrabBytes = new byte[0];
	}

	yield return new WaitForEndOfFrame();
	//*** set initial screensho dimensions
	int width = Screen.width;
	int height = Screen.height;
	
	Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);
	// Read screen contents into the texture
	tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);

	yield return  .5f;

	// we are going to divide the textures size by an eighth of the original screenshots size 
	TextureScale.Bilinear(tex,width/4,height/4);
	   
	//*** here we take the reduced texture  and encode it to bytes
	screenGrabBytes = tex.EncodeToPNG(); 

	//**** here we null out the texture we use for screenshot creation
	tex = null;

	//*** we return the initial texture to a 1 by 1 pixel image
	tex = new Texture2D(0,0);

	//*** here we de-allocate any screenshots or existing data still in the project
	Resources.UnloadUnusedAssets();
}

Does anyone have any recommendations on how I might be able to optimize this screenshot grabbing process or see where my code may be bloating unnecessarily.

the next thing I was going to try is destroying the texture that we create , since I don’t think I am ever deleting it and after grabbing the byte data it’s unnecessary .

So first off, don’t call Resources.UnloadUnusedAssets in this case, it is the cause of your lag spike. Instead just simply save the raw byte data to your file and set the texture reference and the byte array to null. This should release the memory when the garbage collector gets to it.

I used that script myself to downscale screenshots to use as thumbnails for the save/load menu and I remember there being some other quirk. I’ll take a look at my code and let you know if there’s any other things to watch out for.