Created
April 2, 2020 15:22
-
-
Save danielmccluskey/4abf3fda8bf2061ffc2758e25caf49c3 to your computer and use it in GitHub Desktop.
Creates a screenshot on button press
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using UnityEngine; | |
| using System.Collections; | |
| public class ScreenShotter : MonoBehaviour | |
| { | |
| public int resWidth = 1920; | |
| public int resHeight = 1080; | |
| private bool takeHiResShot = false; | |
| public static string ScreenShotName(int width, int height) | |
| { | |
| return string.Format("{0}/screenshots/screen_{1}x{2}_{3}.png", | |
| Application.dataPath, | |
| width, height, | |
| System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss")); | |
| } | |
| public void TakeHiResShot() | |
| { | |
| takeHiResShot = true; | |
| } | |
| void LateUpdate() | |
| { | |
| takeHiResShot |= Input.GetKeyDown("k"); | |
| if (takeHiResShot) | |
| { | |
| RenderTexture rt = new RenderTexture(resWidth, resHeight, 24); | |
| Camera.main.targetTexture = rt; | |
| Texture2D screenShot = new Texture2D(resWidth, resHeight, TextureFormat.RGB24, false); | |
| Camera.main.Render(); | |
| RenderTexture.active = rt; | |
| screenShot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0); | |
| Camera.main.targetTexture = null; | |
| RenderTexture.active = null; // JC: added to avoid errors | |
| Destroy(rt); | |
| byte[] bytes = screenShot.EncodeToPNG(); | |
| string filename = ScreenShotName(resWidth, resHeight); | |
| if (System.IO.Directory.Exists(Application.dataPath + "/screenshots")) | |
| { | |
| System.IO.File.WriteAllBytes(filename, bytes); | |
| Debug.Log(string.Format("Took screenshot to: {0}", filename)); | |
| takeHiResShot = false; | |
| } | |
| else | |
| { | |
| System.IO.Directory.CreateDirectory(Application.dataPath + "/screenshots"); | |
| System.IO.File.WriteAllBytes(filename, bytes); | |
| Debug.Log(string.Format("Took screenshot to: {0}", filename)); | |
| takeHiResShot = false; | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment