In this recipe, we will learn how to take in-game snapshots and save them to an external file. Better yet, we will make it possible to choose between two different methods.
In order to follow this recipe, please import the screenshots
package, available in the 0423_07_06
folder, into your project. This package includes a basic terrain and a camera that can be rotated via a mouse.
To save screenshots from your game, follow these steps:
screenshots
package and open the screenshotLevel
scene.// file: TakeScreenshot.cs using UnityEngine; using System.Collections; using System; using System.IO; public class TakeScreenshot : MonoBehaviour { public string prefix = "Screenshot"; public int scale = 1; public bool useReadPixels = false; private Texture2D texture; void Update (){ if (Input.GetKeyDown (KeyCode.P)) StartCoroutine(TakeShot()); } IEnumerator TakeShot (){ string date = System.DateTime.Now.ToString("_d-MMM-yyyy-HH-mm-ss-f"); int sw = Screen.width; int sh = Screen.height; Rect sRect = new Rect(0,0,sw,sh); if (useReadPixels){ yield return new WaitForEndOfFrame(); texture = new Texture2D (sw,sh,TextureFormat.RGB24,false); texture.ReadPixels(sRect,0,0); texture.Apply(); byte[] bytes= texture.EncodeToPNG(); Destroy (texture); File.WriteAllBytes(Path.GetDirectoryName(Application.dataPath) + Path.DirectorySeparatorChar + prefix + date + ".png", bytes); } else { Application.CaptureScreenshot(prefix + date + ".png", scale); } } }
Once the script has detected that the P key has been pressed, the screen is captured and stored as an image file in the same folder where the executable is. Unless Use Read Pixels is selected, the script will call a built-in Unity function called CaptureScreenshot()
, which is capable of scaling up the original screen size (in our case, based on the Scale
variable of our script).
We have included the Use Read Pixel option as a demonstration of how to save your images to disk without using Unity's CaptureScreenshot()
function. One advantage of this method is that it can be adapted to capture and save only a portion of the screen. The Scale
variable from our script will not affect it needs, though.
18.191.186.219