以下是一个示例的Unity拍照脚本,用于拍摄相机看到的内容并保存在工程根目录下:
using System;
using UnityEngine;
using System.IO;
public class CameraCapture : MonoBehaviour
{
public Camera captureCamera; // 要拍摄的相机
public void CaptureScreenshot()
{
string filePath = Path.Combine(Application.dataPath, "screenshot.png");
if (File.Exists(filePath))
{
File.Delete(filePath);
}
RenderTexture renderTexture = new RenderTexture(Screen.width, Screen.height, 24);
captureCamera.targetTexture = renderTexture;
captureCamera.Render();
RenderTexture.active = renderTexture;
Texture2D screenshot = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
screenshot.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
screenshot.Apply();
byte[] bytes = screenshot.EncodeToPNG();
File.WriteAllBytes(filePath, bytes);
RenderTexture.active = null;
captureCamera.targetTexture = null;
renderTexture.Release();
Debug.Log("截图已保存至:" + filePath);
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.C))
{
CaptureScreenshot();
}
}
}
要使用该脚本,将其附加到一个游戏对象上,然后将要拍摄的相机指定给captureCamera
变量。可以通过调用CaptureScreenshot()
方法来进行拍照,它会将截图保存在工程根目录下的screenshot.png
文件中。