using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using UnityEngine.UI; public class Screenshot : MonoBehaviour { [SerializeField] RawImage _previewImg; [SerializeField] Camera _capturecam; // Update is called once per frame void Update() { /* if (Input.GetKeyDown(KeyCode.P)) { CreatePreview(); }*/ } public void OnClickTakeScreenshot() { StartCoroutine(TakeScreenshot()); } public void OnClickPreview() { CreatePreview(); } public void DestroyPreviewTexture() { if (_previewImg.texture == true) { Destroy(_previewImg.texture); } } IEnumerator TakeScreenshot() { yield return new WaitForEndOfFrame(); string timpStamp = DateTime.Now.ToString("ddMMyyyyHHmmssffff"); ScreenCapture.CaptureScreenshot("snapshot_" + timpStamp + ".png"); } void CreatePreview() { _capturecam.enabled = true; RenderTexture screenTexture = new RenderTexture(Screen.width, Screen.height, 16); _capturecam.targetTexture = screenTexture; RenderTexture.active = screenTexture; _capturecam.Render(); Texture2D renderedTexture = new Texture2D(Screen.width, Screen.height); renderedTexture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0); renderedTexture.Apply(); RenderTexture.active = null; _capturecam.enabled = false; _previewImg.texture = renderedTexture; // Save texture in png file byte[] byteArray = renderedTexture.EncodeToPNG(); string timpStamp = DateTime.Now.ToString("ddMMyyyyHHmmssffff"); System.IO.File.WriteAllBytes(Application.persistentDataPath + $"/snapshot_{timpStamp}.png", byteArray); } }