Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.IO;
- using UnityEngine;
- using UnityEngine.Rendering;
- namespace Winglett.RR.Utils
- {
- [RequireComponent(typeof(Camera))]
- public class Screenshotter : MonoBehaviour
- {
- public bool m_TakeScreenshot;
- public CameraEvent m_CamEvent;
- private Camera m_Camera;
- private CommandBuffer m_Buffer;
- private RenderTexture m_Rt;
- private void Awake()
- {
- m_Camera = GetComponent<Camera>();
- m_Buffer = new CommandBuffer();
- m_Rt = new RenderTexture(m_Camera.pixelWidth, m_Camera.pixelHeight, 0);
- }
- private void Update()
- {
- if (m_TakeScreenshot)
- {
- TakeScreenshot();
- m_TakeScreenshot = false;
- }
- }
- public void TakeScreenshot()
- {
- m_Buffer.Blit(BuiltinRenderTextureType.CurrentActive, new RenderTargetIdentifier(m_Rt));
- m_Buffer.RequestAsyncReadback(m_Rt, (AsyncGPUReadbackRequest obj) =>
- {
- StartCoroutine(ProcessScreenshot(obj));
- });
- m_Camera.AddCommandBuffer(m_CamEvent, m_Buffer);
- }
- private IEnumerator ProcessScreenshot(AsyncGPUReadbackRequest request)
- {
- m_Camera.RemoveCommandBuffer(m_CamEvent, m_Buffer);
- var rawData = request.GetData<Color32>();
- Color32[] data = rawData.ToArray();
- yield return null;
- Texture2D tex = new Texture2D(m_Camera.pixelWidth, m_Camera.pixelHeight);
- tex.SetPixels32(data);
- tex.Apply();
- yield return null;
- string path = Path.Combine(UnityEngine.Application.persistentDataPath, "test.png");
- File.WriteAllBytes(path, tex.EncodeToPNG());
- yield return null;
- Debug.Log("Screenshot done");
- Destroy(tex);
- }
- private void OnDestroy() => m_Rt.Release();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement