在Unity3D中利用 RenderTexture 实现游戏内截图

时间:2023-03-09 03:50:06
在Unity3D中利用 RenderTexture 实现游戏内截图
 using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine; public class 截图 : MonoBehaviour { private void Update()
{
if(Input.GetKeyDown(KeyCode.S))
{
Debug.Log("Save");
Save();
}
} private RenderTexture TargetTexture; private void OnRenderImage(RenderTexture source, RenderTexture destination)
{
TargetTexture = source;
Graphics.Blit(source, destination);
} private void Save()
{
RenderTexture.active = TargetTexture; Texture2D png = new Texture2D(RenderTexture.active.width, RenderTexture.active.height, TextureFormat.ARGB32, true);
png.ReadPixels(new Rect(, , RenderTexture.active.width, RenderTexture.active.height), , ); byte[] bytes = png.EncodeToPNG();
string path = string.Format(@"D:\123.png");
FileStream file = File.Open(path, FileMode.Create);
BinaryWriter writer = new BinaryWriter(file);
writer.Write(bytes);
file.Close();
writer.Close(); Destroy(png);
png = null; Debug.Log("Save Down");
}
}

功能:

点击 S 截图。

该脚本需要挂载在相机上。

OnRenderImage 是Unity内置的事件,会在GPU渲染完场景之后,渲染到屏幕之前执行。两个参数,一个是GPU渲染完成的图片,第二个参数会在调用完该事件之后渲染到屏幕上。

该事件可以用来做屏幕后处理,但是我们在这里用来拦截渲染的图片,保存下来之后再归还。

在Unity3D中利用 RenderTexture 实现游戏内截图在Unity3D中利用 RenderTexture 实现游戏内截图