Advertisement
Guest User

Screenshots in Unity 2019

a guest
Sep 26th, 2019
295
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.85 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEditor;
  5. using System.IO;
  6.  
  7. public class ScreenshotManager : MonoBehaviour
  8. {
  9.     public static ScreenshotManager st;
  10.  
  11.     public List<Sprite> screenshots;
  12.  
  13.     Camera cam;
  14.  
  15.     void Awake()
  16.     {
  17.         st = this;
  18.         cam = GetComponent<Camera>();
  19.     }
  20.  
  21.     public void TakeScreenshot()
  22.     {
  23.         cam = GetComponent<Camera>();
  24.         RenderTexture renderTexture = new RenderTexture(Screen.width, Screen.height, 24);
  25.         cam.targetTexture = renderTexture;
  26.         cam.Render();
  27.         cam.targetTexture = null;
  28.  
  29.         RenderTexture.active = renderTexture;
  30.         Texture2D screenshot = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
  31.         screenshot.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
  32.         screenshot.Apply();
  33.         RenderTexture.active = null;
  34.  
  35.         byte[] bytes = screenshot.EncodeToPNG();
  36.         Destroy(screenshot);
  37.  
  38.         DirectoryInfo screenshotsDirectory = new DirectoryInfo(Application.dataPath + "/Resources/Screenshots/");
  39.         FileInfo[] dirInfo = screenshotsDirectory.GetFiles();
  40.         int number = 0;
  41.         foreach (var item in dirInfo)
  42.         {
  43.             number++;
  44.         }
  45.  
  46.         string name = "Screenshot" + number + ".png";
  47.         File.WriteAllBytes(Application.dataPath + "/Resources/Screenshots/" + name, bytes);
  48.  
  49.         AssetDatabase.Refresh();
  50.  
  51.         // DISPLAYS THE SCREENSHOT ON AN IMAGE
  52.         var t2d = AssetDatabase.LoadAssetAtPath("Assets/Resources/Screenshots/" + name, typeof(Texture2D)) as Texture2D;
  53.         Sprite spr = Sprite.Create(t2d, new Rect(0, 0, t2d.width, t2d.height), new Vector2(.5f, .5f));
  54.         CanvasManager.st.DisplayScreenshot(spr as Sprite);
  55.     }
  56.  
  57.     // TODO: Make screenshot system work in built mode.
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement