Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2019
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.02 KB | None | 0 0
  1. using System.Collections;
  2. using System.IO;
  3. using UnityEngine;
  4. using UnityEngine.Rendering;
  5.  
  6. namespace Winglett.RR.Utils
  7. {
  8.     [RequireComponent(typeof(Camera))]
  9.     public class Screenshotter : MonoBehaviour
  10.     {
  11.         public bool m_TakeScreenshot;
  12.         public CameraEvent m_CamEvent;
  13.  
  14.         private Camera m_Camera;
  15.         private CommandBuffer m_Buffer;
  16.         private RenderTexture m_Rt;
  17.  
  18.         private void Awake()
  19.         {
  20.             m_Camera = GetComponent<Camera>();
  21.             m_Buffer = new CommandBuffer();
  22.             m_Rt = new RenderTexture(m_Camera.pixelWidth, m_Camera.pixelHeight, 0);
  23.         }
  24.  
  25.         private void Update()
  26.         {
  27.             if (m_TakeScreenshot)
  28.             {
  29.                 TakeScreenshot();
  30.                 m_TakeScreenshot = false;
  31.             }
  32.         }
  33.  
  34.         public void TakeScreenshot()
  35.         {
  36.             m_Buffer.Blit(BuiltinRenderTextureType.CurrentActive, new RenderTargetIdentifier(m_Rt));
  37.  
  38.             m_Buffer.RequestAsyncReadback(m_Rt, (AsyncGPUReadbackRequest obj) =>
  39.             {
  40.                 StartCoroutine(ProcessScreenshot(obj));
  41.             });
  42.  
  43.             m_Camera.AddCommandBuffer(m_CamEvent, m_Buffer);
  44.         }
  45.  
  46.         private IEnumerator ProcessScreenshot(AsyncGPUReadbackRequest request)
  47.         {
  48.             m_Camera.RemoveCommandBuffer(m_CamEvent, m_Buffer);
  49.             var rawData = request.GetData<Color32>();
  50.             Color32[] data = rawData.ToArray();
  51.  
  52.             yield return null;
  53.  
  54.             Texture2D tex = new Texture2D(m_Camera.pixelWidth, m_Camera.pixelHeight);
  55.             tex.SetPixels32(data);
  56.             tex.Apply();
  57.  
  58.             yield return null;
  59.  
  60.             string path = Path.Combine(UnityEngine.Application.persistentDataPath, "test.png");
  61.             File.WriteAllBytes(path, tex.EncodeToPNG());
  62.  
  63.             yield return null;
  64.  
  65.             Debug.Log("Screenshot done");
  66.             Destroy(tex);
  67.         }
  68.  
  69.         private void OnDestroy() => m_Rt.Release();
  70.     }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement