項目中,遇到需要將相機當前渲染的內容或者是RenderTexture保存到本地的需求,查看渲染結果是否正確。因此,寫了一個簡單的小工具,按F4就可以保存到Assets上一級目錄。
先直接貼代碼,有時間再詳細解釋
使用方式是直接將腳本掛在需要的camera上,按F4保存截圖。
using UnityEngine;
using System;
using System.IO;
public class SaveCamTexture : MonoBehaviour
{
public Camera cam;
public RenderTexture rt;
public void Start()
{
if(cam==null)
{
cam = this.GetComponent<Camera>();
}
}
private void Update()
{
if(cam==null)
{ return; }
if(Input.GetKeyDown(KeyCode.F4))
{
_SaveCamTexture();
}
}
private void _SaveCamTexture()
{
rt = cam.targetTexture;
if(rt!=null)
{
_SaveRenderTexture(rt);
rt = null;
}
else
{
GameObject camGo = new GameObject("camGO");
Camera tmpCam = camGo.AddComponent<Camera>();
tmpCam.CopyFrom(cam);
// rt = new RenderTexture(Screen.width, Screen.height, 16, RenderTextureFormat.ARGB32);
rt =RenderTexture.GetTemporary(Screen.width,Screen.height,16, RenderTextureFormat.ARGB32);
tmpCam.targetTexture = rt;
tmpCam.Render();
_SaveRenderTexture(rt);
Destroy(camGo);
//rt.Release();
RenderTexture.ReleaseTemporary(rt);
//Destroy(rt);
rt = null;
}
}
private void _SaveRenderTexture(RenderTexture rt)
{
RenderTexture active = RenderTexture.active;
RenderTexture.active = rt;
Texture2D png = new Texture2D(rt.width, rt.height, TextureFormat.ARGB32, false);
png.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
png.Apply();
RenderTexture.active = active;
byte[] bytes = png.EncodeToPNG();
string path = string.Format("Assets/../rt_{0}_{1}_{2}.png", DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
FileStream fs = File.Open(path, FileMode.Create);
BinaryWriter writer = new BinaryWriter(fs);
writer.Write(bytes);
writer.Flush();
writer.Close();
fs.Close();
Destroy(png);
png = null;
Debug.Log("保存成功!"+path);
}
}
文檔中說,可以使用RenderTexture.GetTemporary()方法來獲取RenderTexture池中的一個(如果尺寸匹配),速度回比較快;並且,對應的使用RenderTexture。ReleaseTemporary()來釋放。
此方法適用於需要一個renderTexture做一些臨時的計算時候使用。
試了一下,之前保存圖片的時候有明顯的卡頓,而改過之後,卡頓明顯改善。