しっぽを追いかけて

ぐるぐるしながら考えています

Unity と猫の話題が中心   掲載内容は個人の私見であり、所属組織の見解ではありません

Unity で画面キャプチャして画像ファイルに保存する

※ これは 2021/06/18 時点の Unity 2021.1.12f1 の情報です

最新版では動作が異なる可能性がありますのでご注意ください

とりあえず脱出ゲームに使えるようなレンダリングができるようになったので、今度は UnityEditorレンダリング画面をそのまま画像ファイルとして保存したい

実際のゲーム上で HDRPレンダリングをするとモバイルなど非力なデバイスだと負荷がかかるため、必要な場面分だけあらかじめ 2D 画像化してしまい、この画像を実際のアプリで表示するようにしたい

そこで用意したのが次のスクリプト

using System.IO;
using UnityEditor;
using UnityEngine;

[ExecuteInEditMode]
public class ScreenCapture
{
    [MenuItem("Tools/Screen Capture")]
    public static void Capture()
    {
        // Game 画面のサイズを取得
        var size = new Vector2Int((int)Handles.GetMainGameViewSize().x, (int)Handles.GetMainGameViewSize().y);
        var render = new RenderTexture(size.x, size.y, 24);
        var texture = new Texture2D(size.x, size.y, TextureFormat.RGB24, false);
        var cemara = Camera.main;

        try
        {
            // カメラ画像を RenderTexture に描画
            cemara.targetTexture = render;
            cemara.Render();

            // RenderTexture の画像を読み取る
            RenderTexture.active = render;
            texture.ReadPixels(new Rect(0, 0, size.x, size.y), 0, 0);
            texture.Apply();
        }
        finally
        {
            cemara.targetTexture = null;
            RenderTexture.active = null;
        }

        // PNG 画像としてファイル保存
        File.WriteAllBytes(
            $"{Application.dataPath}/image.png",
            texture.EncodeToPNG());
    }
}

RenderTexture を経由してカメラの描画結果を Texture2D に出力し、PNG 画像ファイルとして保存

コンパイルが終わると Tools/Screen Capture のメニューがウィンドウに追加されるのでこれを実行

画面キャプチャメニュー

すると Assets 直下に現在の Main Camera の内容がそのまま image.png として保存された!

キャプチャ画像を保存