Skip to content

Instantly share code, notes, and snippets.

@pofulu
Created April 6, 2019 05:21
Show Gist options
  • Save pofulu/8d0ddf4ae5045438631537c881bbcbae to your computer and use it in GitHub Desktop.
Save pofulu/8d0ddf4ae5045438631537c881bbcbae to your computer and use it in GitHub Desktop.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[Serializable]
public class RenderSource
{
public Camera targetCamera;
public RenderTexture targetTexture;
public int width { get; private set; }
public int height { get; private set; }
private Texture2D texture;
private RenderTexture renderTexture;
bool initialized;
public void Init(int width, int height)
{
this.width = width;
this.height = height;
texture = new Texture2D(width, height, TextureFormat.RGB24, false, true);
renderTexture = new RenderTexture(width, height, 24);
initialized = true;
}
public Texture2D FetchOnce()
{
var fetch = Fetch();
Release();
return fetch;
}
public Texture2D Fetch()
{
if (!initialized)
throw new Exception("請先執行 Init()");
if (targetCamera)
{
targetCamera.targetTexture = renderTexture;
targetCamera.Render();
RenderTexture.active = renderTexture;
texture.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
texture.Apply();
targetCamera.targetTexture = null;
return texture;
}
else if (targetTexture)
{
RenderTexture.active = targetTexture;
texture.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
texture.Apply();
return texture;
}
else
{
throw new Exception("至少指定 targetCamera 或 targetTexture 其中一項");
}
}
public void Release()
{
RenderTexture.active = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment