基于当前主相机的RenderTexture,好处是可以自定义分辨率等参数,脚本会输出品质为100的jpg序列,基本无损。
而用Application.CaptureScreenshot虽然可以录制包括OnGUI在内全部内容,但有是会png文件头损坏而无法输出视频,且分辨率不可设置
需要注意,unity不会按照渲染帧率来运行,如果是录制用来渲染需要另外写一个时间,用这个每帧间隔相等的时间驱动动画。
用管理员权限运行Unity,脚本挂在任意节点上,运行自动录制。
第二次运行自动删除之前录制的内容,重新录制
using UnityEngine; using System.IO; public class RealtimeScreenRecorder : MonoBehaviour { public TextureFormat textureFormat = TextureFormat.RGB24; public int width = 1280; public int height = 720; [Header("Example D:/Test/Images/{0:0000}[{1}]")] public string savePath; Texture2D mTmpTexture2D; RenderTexture mRenderTexture; RenderTexture RenderTexture { get { if (mRenderTexture == null) { mRenderTexture = new RenderTexture(width, height, 24); } return mRenderTexture; } } Texture2D TmpTexture2D { get { if (mTmpTexture2D == null) mTmpTexture2D = new Texture2D(width, height, textureFormat, false); return mTmpTexture2D; } } public string FileSavePath { get { return string.Format(savePath + ".jpg", Time.frameCount, Time.time); } } void Start() { var outputPath = Path.GetDirectoryName(string.Format(savePath, 0, 0)); if (!Directory.Exists(outputPath)) { Directory.CreateDirectory(outputPath); } else { Directory.Delete(outputPath, true); Directory.CreateDirectory(outputPath); //clear old images. } } void Update() { if (Camera.main == null) return; RenderTexture.active = RenderTexture; Camera.main.targetTexture = RenderTexture; Camera.main.Render(); TmpTexture2D.ReadPixels(new Rect(0, 0, width, height), 0, 0); TmpTexture2D.Apply(); File.WriteAllBytes(FileSavePath, TmpTexture2D.EncodeToJPG(100)); Camera.main.targetTexture = null; RenderTexture.active = null; } void OnDestroy() { RenderTexture.Release(); DestroyObject(RenderTexture); DestroyObject(mTmpTexture2D); System.GC.Collect(); } }
RealtimeScreenRecorder.cs
录制效果,支持相机滤镜:
时间: 2024-10-26 03:04:40