ランタイムでカメラの写してる画像を保存しようとしてもタイミングを考慮しないと
正しく画像を撮影することができません
そのため WaitForEndOffFrame
でレンダリングの完了を待つ必要があります
yield return new WaitForEndOffFrame();
コード
レンダリングを待ちつつ、画像の保存を行うコードが以下です
using System.Collections; using UnityEngine; public class CameraRender { // カメラ映像を保存 public static IEnumerator Save(Camera camera, Vector2Int size, string savePath) { // 今のフレームでのカメラのレンダリングを待つ yield return new WaitForEndOffFrame(); var renderTexture = new RenderTexture(size.x, size.y, 0); camera.targetTexture = renderTextre; // カメラの描画をテクスチャーに書き込み camera.Render(); // 現在のアクティブなRenderTextuerをキャッシュ var cache = RenderTexture.active; // Pixel情報を読み込むためにアクティブに指定 RenderTexture.active = renderTextre; var texture = new Texture2D(size.x, size.y, TextureFormat.RGB24, false); // RenderTexture.activeから読み込み texture.ReadPixels(new Rect(0, 0, size.x, size.y), 0, 0); // テクスチャの保存 texture.Applay(); try { System.IO.WriteAllBytes(savePath, texture.EncodeToPng()); } catch { } RenderTexture.active = cache; camera.targetTexture = null; Destroy(renderTexture); yield return null; } }