【Unity】背景をアルファ0でスクリーンショットを撮る

はじめに

ScreenCapture クラスを使用して ゲーム画面をキャプチャすることができますが,
背景を透過してキャプチャしたかったのでクラスを作成しました。
docs.unity3d.com

完成図

ゲーム画面

キャプチャ結果

コード

public static class ScreenCapture
{
    public static void Capture(Camera targetCamera, Vector2Int captureSize)
    {
        // デスクトップに保存
        string desktopDirectoryPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
        var path = desktopDirectoryPath + "/" + DateTime.Now.ToString("yyyyMMdd-HHmmss") + ".png";

        var screenShot = new Texture2D(captureSize.x, captureSize.y, TextureFormat.ARGB32, false);
        var renderTexture = new RenderTexture(screenShot.width, screenShot.height, 32);
        targetCamera.clearFlags = CameraClearFlags.SolidColor;
        targetCamera.backgroundColor = new Color(0, 0, 0, 0);
        var prev = targetCamera.targetTexture;
        targetCamera.targetTexture = renderTexture;
        targetCamera.Render();
        targetCamera.targetTexture = prev;
        RenderTexture.active = renderTexture;
        screenShot.ReadPixels(new Rect(0, 0, screenShot.width, screenShot.height), 0, 0);
        screenShot.Apply();

        var bytes = screenShot.EncodeToPNG();
        UnityEngine.Object.DestroyImmediate(screenShot);
        File.WriteAllBytes(path, bytes);

        Debug.Log("ScreenCaptre: " + path);
    }
}