I have a coroutine that takes a screenshot and saves to the file system. But when the coroutine runs the game freezes momentarily and the event onFinishedScreenShot
fires prematurely.
I thought that Coroutines were "on a background thread".
Is there a way to adjust my code save a screenshot without blocking the main thread and have the event onFinishedScreenShot
fire AFTER the write file is finished? Or is there a better way of handling saving screenshots for games?
MySingleton.cs
public event Action<string> onFinishedScreenShot;
public IEnumerator TakeScreenshot(string filename) {
Texture2D areaImage = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
yield return new WaitForEndOfFrame();
areaImage.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0, false);
areaImage.Apply();
byte[] bytes = areaImage.EncodeToPNG();
File.WriteAllBytes(filename, bytes);
if (onFinishedScreenShot != null) {
onFinishedScreenShot(filename);
}
}
AnotherClass.cs
private void Start() {
LoadTexture(someFileName);
}
public void SomeMethodInAnotherClass() {
StartCoroutine(MySingleton.TakeScreenshot(someFileName));
}
public void LoadTexture(string filename) {
if (!filename.Equals("NOT SET") ) {
byte[] bytes = File.ReadAllBytes(GetSaveFilename(filename));
Texture2D texture = new Texture2D(500, 500, TextureFormat.DXT5, false);
texture.filterMode = FilterMode.Trilinear;
texture.LoadImage(bytes);
RectTransform rt = locationSnapShot.rectTransform;
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, rt.rect.width, rt.rect.height), new Vector2(0.5f, 0.0f), 16.0f);
locationSnapShot.sprite = sprite;
Debug.Log("Removing event listener.");
MySingleton.onFinishedScreenShot -= LoadTexture;
} else {
Debug.Log("No screen shot. Listening for a change.");
MySingleton.onFinishedScreenShot += LoadTexture;
}
}