如何使用 C# 在 Unity 中截取我的桌面应用程序的当前视图的屏幕截图?

How do I take a screenshot of the current view of my desktop app in Unity using C#?

我有一个在 Unity 上制作的桌面应用程序,我想使用附加到主摄像头的 C# 脚本截取应用程序中当前视图的屏幕截图。请帮忙。

我浏览了在此平台上找到的其他代码片段,但似乎没有任何帮助。

您可以使用 CaptureScreenshot.

public class ScreenCapture : MonoBehaviour
{
    //here you can set the folder you want to use, 
    //IMPORTANT - use "@" before the string, because this is a verbatim string
    //IMPORTANT - the folder must exists
    string pathToYourFile = @"C:\Screenshots\";
    //this is the name of the file
    string fileName = "filename";
    //this is the file type
    string fileType = ".png";

    private int CurrentScreenshot { get => PlayerPrefs.GetInt("ScreenShot"); set => PlayerPrefs.SetInt("ScreenShot", value); }

    private void Update()
    {

        if (Input.GetKeyDown(KeyCode.Space))
        {
            UnityEngine.ScreenCapture.CaptureScreenshot(pathToYourFile + fileName + CurrentScreenshot + fileType);
            CurrentScreenshot++;
        }
    }
}

一些注意事项。

  1. 我使用逐字字符串来定义您的文件夹
  2. 你存放截图的文件夹必须存在(如果你想在脚本中创建它you can follow this answer
  3. AFTER COMMENT REQUEST - 1:如果你没有设置文件夹,文件将保存在应用程序的默认目录中(根据系统而变化 - 你可以从 Application.dataPath)
  4. 检查
  5. AFTER COMMENT REQUEST - 2:如果您使用相同的路径和文件名,文件将被覆盖,所以我添加了一种方法让您保存多个屏幕截图,同样在不同的使用 PlayerPrefs.
  6. 的会话

您可以使用上面回答的 CaptureScreenshot 方法,但如果您不熟悉 unity,可能会感到困惑。它将您捕获的图像存储在文件路径中,您应该将其作为参数传递给 CaptureScreenshot 方法,例如

public class ScreenShotManager : MonoBehaviour {

const string FilePath = @"C:\Users\UserName\Desktop\ScreenShots";

public void CaptureScreenShot() {
    ScreenCapture.CaptureScreenshot(FilePath);
}

void Update(){
    if(Input.GetKeyDown(Keycode.C))
        CaptureScreenShot();
}

此代码显示,如果您按键盘上的 'c' 键,它将捕获当时正在渲染的主相机并存储在该文件路径中