Capture Screenshot in Unity

Screenshots can be created very easily in Unity using the ScreenCapture class respectively the CaptureScreenshot method. You can use the class defined below. Just create a new script CaptureScreenshot.cs and paste the code there. Then you just have to attach the new MonoBehaviour to a GameObject. You can select the folder and the key afterwards simply inside the Inspector. Screenshots will be saved in your system folder Pictures.

using UnityEngine;

public class CaptureScreenshot : MonoBehaviour
{
    private string _screenshotDirectory;

    // Define the button which will trigger the screenshot function.
    public KeyCode key = KeyCode.F11;

    // The name of the folder within our pictures folder.
    public string folder = "my-folder";

    void Start()
    {
        _screenshotDirectory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyPictures) + "/" + folder;

        // Make sure our target directory exists.
        System.IO.Directory.CreateDirectory(_screenshotDirectory);
    }

    void Update()
    {
        if (Input.GetKeyDown(key)) {
            StartCoroutine(CaptureScreenshot());
        }
    }

    IEnumerator CaptureScreenshot()
    {
        yield return null;

        // Take the actual screenshot.
        string filename = "screenshot-w" + Screen.width + "-h" + Screen.height + "-" + System.DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss") + ".png";
        ScreenCapture.CaptureScreenshot(_screenshotDirectory + "/" + filename);

        // Just for debugging, log the path where the screenshot was stored.
        Debug.Log("Screenshot taken: " + _screenshotDirectory + "/" + filename);
    }
}