using System; using System.IO; using System.Threading; using System.Threading.Tasks; using UnityEngine; namespace Crowdin.Plugin.Views { using Helpers; public class TakeScreenshotForCrowdin { private Texture2D screenshot; public event Action OnScreenshotTacked; public void TakeScreenshot(CancellationToken cancellationToken = default) { ProcessTakeScreenshot(cancellationToken) .ContinueWith(task => { if (task.Exception is not null) { Debug.Log($"Error: {task.Exception.Message}"); } }); } private async Task ProcessTakeScreenshot(CancellationToken cancellationToken) { var epochStart = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); var key = $"{Application.productName}_{(DateTime.UtcNow - epochStart).TotalSeconds}"; var imageName = $"{FolderHelper.screenshotsDirectory}/{key}.png"; try { // Take the screenshot ScreenCapture.CaptureScreenshot(imageName); // Wait because CaptureScreenshot execution may not be completed await Task.Delay(500, cancellationToken); // Read the data from the file byte[] data = await File.ReadAllBytesAsync(imageName, cancellationToken); // Create the texture var screenshotTexture = new Texture2D(Screen.width, Screen.height); // Load the image screenshotTexture.LoadImage(data); // Fire event captured OnScreenshotTacked?.Invoke(imageName, screenshotTexture); } catch (OperationCanceledException) { // Popup closed mid-capture: don't let the capture finish and still fire // OnScreenshotTacked (which would go on to upload the screenshot). if (File.Exists(imageName)) { File.Delete(imageName); } throw; } } } }