Created
April 6, 2019 05:21
-
-
Save pofulu/8d0ddf4ae5045438631537c881bbcbae to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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