使用ChatGPT写了一个Unity中截图当前场景并保存到本地的代码片

以下是GPT的回答:

在此代码中,我们使用RenderTexture来捕捉摄像机渲染的图像。使用RenderTexture有两个好处。首先,它允许我们截取摄像机渲染的图像而不是整个屏幕。其次,我们可以通过RenderTexture来读取图像数据,而不是直接从屏幕上读取数据。在Update方法中,我们检测是否按下了S键,如果是,则执行以下操作:

  1. 创建一个RenderTexture对象,将其设置为当前摄像机的目标纹理。
  2. 创建一个Texture2D对象,并将RenderTexture对象中的像素数据读取到Texture2D对象中。
  3. 重置摄像机的目标纹理,销毁RenderTexture对象。
  4. 将Texture2D对象转换为PNG格式的字节数组,并保存到本地文件中。

请注意,我们将图像保存到应用程序数据文件夹中。这是因为我们无法直接将图像保存到项目文件夹中,必须将其保存到应用程序数据文件夹或其他位置。

using UnityEngine;
using System.IO;

public class ScreenShot : MonoBehaviour
{
    
    
    public int captureWidth = 1920;
    public int captureHeight = 1080;
    private Camera mainCamera;

    void Start()
    {
    
    
        mainCamera = Camera.main;
    }

    void Update()
    {
    
    
        if (Input.GetKeyDown(KeyCode.S))
        {
    
    
            string fileName = "screenshot.png";
            string path = Path.Combine(Application.dataPath, fileName);

            RenderTexture rt = new RenderTexture(captureWidth, captureHeight, 24);
            mainCamera.targetTexture = rt;
            Texture2D screenShot = new Texture2D(captureWidth, captureHeight, TextureFormat.RGB24, false);
            mainCamera.Render();
            RenderTexture.active = rt;
            screenShot.ReadPixels(new Rect(0, 0, captureWidth, captureHeight), 0, 0);
            mainCamera.targetTexture = null;
            RenderTexture.active = null;
            Destroy(rt);

            byte[] bytes = screenShot.EncodeToPNG();
            File.WriteAllBytes(path, bytes);
            Debug.Log("Screenshot saved to " + path);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/Czhenya/article/details/130061753
今日推荐