unity pc截图保存
时间: 2023-09-23 16:04:45 浏览: 81
您好,关于Unity PC截图保存的问题,可以使用以下代码实现:
```
using UnityEngine;
using System.IO;
public class ScreenShot : MonoBehaviour
{
public int captureWidth = 1920;
public int captureHeight = 1080;
private string captureDirectory = @"C:\Screenshots\";
void Update ()
{
if (Input.GetKeyDown(KeyCode.S))
{
TakeShot();
}
}
void TakeShot()
{
// Create directory if it does not exist
if (!Directory.Exists(captureDirectory))
Directory.CreateDirectory(captureDirectory);
// Define image name with timestamp
string timeStamp = System.DateTime.Now.ToString("yyyyMMdd-HHmmss");
string fileName = "screenshot_" + timeStamp + ".png";
string path = captureDirectory + fileName;
// Capture screenshot
Texture2D screenShot = new Texture2D(captureWidth, captureHeight, TextureFormat.RGB24, false);
RenderTexture rt = new RenderTexture(captureWidth, captureHeight, 24);
Camera camera = Camera.main;
camera.targetTexture = rt;
RenderTexture.active = rt;
camera.Render();
screenShot.ReadPixels(new Rect(0, 0, captureWidth, captureHeight), 0, 0);
camera.targetTexture = null;
RenderTexture.active = null;
Destroy(rt);
// Encode image and save to file
byte[] bytes = screenShot.EncodeToPNG();
using (FileStream file = File.OpenWrite(path))
{
file.Write(bytes, 0, bytes.Length);
}
Debug.Log("Screenshot captured: " + path);
}
}
```
该代码将在按下"S"键时,截取主摄像机当前的画面,并将其保存在"C:\Screenshots\"目录下,以"yyyyMMdd-HHmmss"格式的时间戳命名。如有需要,可以根据实际情况更改保存路径和文件名。希望能对您有所帮助。
阅读全文
相关推荐















