using System.Collections; using System.Runtime.InteropServices; using UnityEngine; public class WebGLDownload : MonoBehaviour { public enum ImageFormat { jpg, png } private bool _isRecording = false; [DllImport("__Internal")] private static extern void DownloadFileJsLib(byte[] byteArray, int byteLength, string fileName); /// /// ___ /// bytes -> The bytes to be downloaded /// fileName -> The downloaded file name (without extension) /// fileExtension -> WebGLDownload.FileExtension.jpg/png/zip/ /// public static void DownloadFile(byte[] bytes, string fileName, string fileExtension) { if (fileName == "") fileName = "UnnamedFile"; #if UNITY_EDITOR string path = UnityEditor.EditorUtility.SaveFilePanel("Save file...", "", fileName, fileExtension); System.IO.File.WriteAllBytes(path, bytes); Debug.Log("File saved: " + path); #elif UNITY_WEBGL DownloadFileJsLib(bytes, bytes.Length, fileName + "." + fileExtension); #endif } /// /// ___ /// imageFormat -> WebGLDownload.ImageFormat.jpg/png /// screenshotUpscale -> Upscale the frame. default = 1 /// fileName -> Optional filename. Empty filename creates a name texture.width x texture.height in pixel + current datetime /// public void GetScreenshot(ImageFormat imageFormat, int screenshotUpscale, string fileName = "") { if (!_isRecording) StartCoroutine(RecordUpscaledFrame(imageFormat, screenshotUpscale, fileName)); } IEnumerator RecordUpscaledFrame(ImageFormat imageFormat, int screenshotUpscale, string fileName) { _isRecording = true; yield return new WaitForEndOfFrame(); try { if (fileName == "") { int resWidth = Camera.main.pixelWidth * screenshotUpscale; int resHeight = Camera.main.pixelHeight * screenshotUpscale; string dateFormat = "yyyy-MM-dd-HH-mm-ss"; fileName = resWidth.ToString() + "x" + resHeight.ToString() + "px_" + System.DateTime.Now.ToString(dateFormat); } Texture2D screenShot = ScreenCapture.CaptureScreenshotAsTexture(screenshotUpscale); if (imageFormat == ImageFormat.jpg) DownloadFile(screenShot.EncodeToJPG(), fileName, "jpg"); else if (imageFormat == ImageFormat.png) DownloadFile(screenShot.EncodeToPNG(), fileName, "png"); Object.Destroy(screenShot); } catch (System.Exception e) { Debug.Log("Original error: " + e.Message); } _isRecording = false; } }