コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】ゲーム画面を背景透過でスクリーンショットできる関数

ソースコード

using System.IO;
using UnityEngine;

namespace Kogane
{
    public static class ScreenCapture
    {
        public static void CaptureScreenshot
        (
            string path,
            Camera camera        = null,
            bool   isTransparent = true
        )
        {
            if ( camera == null )
            {
                camera = Camera.main;
            }

            var width         = camera.pixelWidth;
            var height        = camera.pixelHeight;
            var renderTexture = new RenderTexture( width, height, 32 );
            var texture2D     = new Texture2D( width, height, isTransparent ? TextureFormat.ARGB32 : TextureFormat.RGB24, false );

            camera.targetTexture = renderTexture;
            camera.Render();
            RenderTexture.active = renderTexture;
            texture2D.ReadPixels( new Rect( 0, 0, width, height ), 0, 0 );
            texture2D.Apply();
            RenderTexture.active = null;
            camera.targetTexture = null;
            Object.DestroyImmediate( renderTexture );
            File.WriteAllBytes( path, texture2D.EncodeToPNG() );
        }
    }
}

使用例

// 背景透過あり
ScreenCapture.CaptureScreenshot( "1.png" );

// 背景透過なし
ScreenCapture.CaptureScreenshot( "2.png", isTransparent: false );