Search code examples
c#unity-game-enginescreenshot

Unity screenshot error: capturing the editor too


I'm trying to create some screenshots but ScreenCapture.CaptureScreenshot actually captures the entire editor and not just the Game view.

error

public class ScreenShotTaker : MonoBehaviour
{
    public KeyCode takeScreenshotKey = KeyCode.S;
    public int screenshotCount = 0;
    private void Update()
    {
        if (Input.GetKeyDown(takeScreenshotKey))
        {
            ScreenCapture.CaptureScreenshot("Screenshots/"
                 + "_" + screenshotCount + "_"+ Screen.width + "X" +     Screen.height + "" + ".png");
            Debug.Log("Screenshot taken.");
        }
    }
}    

What could be the issue? How to take a decent, game view only screenshot that includes the UI?

Note, the UI thing, I found other methods online to take a screenshot (using RenderTextures) but those didn't include the UI. In my other, "real" project I do have UI as well, I just opened this tester project to see if the screenshot issue persists here too.


Solution

  • This is a bug and I suggest you stay away from it for while until ScreenCapture.CaptureScreenshot is mature enough. This function was added in Unity 2017.2 beta so this is the right time to file for a bug report from the Editor. To make it worse, it saves only black and blank image on my computer.


    As for taking screenshots, there other ways to do this without RenderTextures, that will also include the UI in the screenshot too.

    You can read pixels from the screen with Texture2D.ReadPixels then save it with File.WriteAllBytes.

    public KeyCode takeScreenshotKey = KeyCode.S;
    public int screenshotCount = 0;
    
    private void Update()
    {
        if (Input.GetKeyDown(takeScreenshotKey))
        {
            StartCoroutine(captureScreenshot());
        }
    }
    
    IEnumerator captureScreenshot()
    {
        yield return new WaitForEndOfFrame();
        string path = "Screenshots/"
                 + "_" + screenshotCount + "_" + Screen.width + "X" + Screen.height + "" + ".png";
    
        Texture2D screenImage = new Texture2D(Screen.width, Screen.height);
        //Get Image from screen
        screenImage.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
        screenImage.Apply();
        //Convert to png
        byte[] imageBytes = screenImage.EncodeToPNG();
    
        //Save image to file
        System.IO.File.WriteAllBytes(path, imageBytes);
    }