ソースコード
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 );