Unity screenshot error: capturing the editor too

Unity screenshot error: capturing the editor too

我正在尝试创建一些屏幕截图,但 ScreenCapture.CaptureScreenshot 实际上捕获了整个编辑器,而不仅仅是游戏视图。

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.");
        }
    }
}    

可能是什么问题?如何截取包含 UI 的像样的、仅限游戏视图的屏幕截图?

注意,UI的东西,我在网上找到了其他截屏的方法(使用RenderTextures),但那些不包括UI。在我的另一个 "real" 项目中,我也有 UI,我刚刚打开了这个测试项目,看看屏幕截图问题是否仍然存在。

这是一个错误,我建议您暂时远离它,直到 ScreenCapture.CaptureScreenshot 足够成熟。此功能是在 Unity 2017.2 beta 中添加的,因此现在是向编辑器提交错误报告的最佳时机。更糟糕的是,它在我的电脑上只保存黑色和空白图像。


至于截屏,还有其他方法可以在没有 RenderTextures 的情况下执行此操作,这也将在屏幕截图中包含 UI。

您可以使用 Texture2D.ReadPixels 从屏幕读取像素,然后使用 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);
}