all green

プログラム、アプリ作成、Web等備忘録が中心です

Unityで画面をキャプチャーしようとした際に「ReadPixels was called to read pixels from system frame buffer, while not inside drawing frame.」

OnPostRenderで処理するといいらしい


環境
Unity 5.3.1f1


参考

kikikiroku.session.jp

using UnityEngine;
using UnityEngine.Events;
using System.Collections;


/// <summary>
/// 画面キャプチャ
/// カメラに追加して使用する
/// </summary>
public class ScreenCapture : MonoBehaviour
{
	private Texture2D texture;
	private bool capture;
	private UnityAction callback;

	public Texture2D Texture { get { return texture; } }


	/// <summary>
	/// キャプチャ開始
	/// </summary>
	public void Take(UnityAction callback)
	{
		if(texture != null)
		{
			DestroyImmediate(texture);
		}
		this.callback = callback;
		capture = true;
	}

	/// <summary>
	/// OnPostRender
	/// </summary>
	void OnPostRender()
	{
		Debug.Log("OnPostRender capture="+capture);
		if(capture)
		{
			texture = new Texture2D(Screen.width, Screen.height, TextureFormat.ARGB32, false);
			texture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
			texture.Apply();
			capture = false;
			callback.Invoke();
			callback = null;
		}
	}

	/// <summary>
	/// 破棄
	/// </summary>
	public void Destroy()
	{
		if(texture != null)
		{
			DestroyImmediate(texture);
		}
		Destroy(this);
	}
}