使用ChatGPT写了一个Unity中截图当前场景并保存到本地的代码片
写一段Unity中截取当前摄像机渲染场景图片并保存到本地代码
·
以下是GPT的回答:
在此代码中,我们使用RenderTexture来捕捉摄像机渲染的图像。使用RenderTexture有两个好处。首先,它允许我们截取摄像机渲染的图像而不是整个屏幕。其次,我们可以通过RenderTexture来读取图像数据,而不是直接从屏幕上读取数据。在Update方法中,我们检测是否按下了S键,如果是,则执行以下操作:
- 创建一个RenderTexture对象,将其设置为当前摄像机的目标纹理。
- 创建一个Texture2D对象,并将RenderTexture对象中的像素数据读取到Texture2D对象中。
- 重置摄像机的目标纹理,销毁RenderTexture对象。
- 将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);
}
}
}

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。
更多推荐
所有评论(0)