using UnityEditor.Media; using System.Collections; using System.Collections.Generic; using UnityEngine; using System.IO; public class CaptureVideo : MonoBehaviour { MediaEncoder encoder; public Texture2D tex; public RenderTexture rt; public int targetFrameRate = 60; int frameCount = 0; // Start is called before the first frame update void Start() { var videoAttr = new VideoTrackAttributes { frameRate = new MediaRational(targetFrameRate), width = 256, height = 256, includeAlpha = false }; var encodedFilePath = Path.Combine(Path.GetTempPath(), "my_movie.mp4"); Debug.Log(encodedFilePath); if (File.Exists(encodedFilePath)) { File.Delete(encodedFilePath); } tex = new Texture2D((int)videoAttr.width, (int)videoAttr.height, TextureFormat.RGBA32, false); encoder = new MediaEncoder(encodedFilePath, videoAttr); rt = GetComponent().targetTexture; } // Update is called once per frame void Update() { // Graphics.CopyTexture(rt, tex); float expectedFrames = Time.timeSinceLevelLoad * targetFrameRate; if (frameCount < expectedFrames) { // "Unity RenderTexture as Texture2D" (Google) // https://stackoverflow.com/questions/44264468/convert-rendertexture-to-texture2d/44265122#44265122 RenderTexture.active = rt; tex.ReadPixels(new Rect(0, 0, tex.width, tex.height), 0, 0); tex.Apply(); // depth: /** ON GPU, assemble different parts of frame and convert it into the RGBA32 format To start, do a linear space conversion from the depth into the red channel, but this limits depth to 256 values. To upgrade, encode into the other color channels as well for more range, but need to write more code on the decoding side to handle this too. Also consider video compression! Minor changes to color should only have a minor change to depth information, so the last significant bits in conversion should have the least impact on the color. */ encoder.AddFrame(tex); frameCount += 1; } } void OnDestroy() { encoder.Dispose(); } }