[Unity基础]RenderTexture
Posted lyh916
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Unity基础]RenderTexture相关的知识,希望对你有一定的参考价值。
参考链接:
https://www.cnblogs.com/Jimm/p/5951362.html
一.相关API
1.Texture2D.ReadPixels
从RenderTexture.active中复制像素,以左下角为原点。
2.MonoBehaviour.OnPostRender
当相机渲染完所有物体就会调用该方法,并且只有当这个脚本挂在相机时才会调用。
二.测试
新建一个场景,新建一个camera和一个go,把go设置为一个单独的层,让camera单独照这个层,主camera不要照这个层。调整camera的深度和targetTexture。
1 using UnityEngine; 2 using System.Collections; 3 using UnityEngine.UI; 4 using System.IO; 5 6 public class TestRenderTexture : MonoBehaviour { 7 8 public Camera camera; 9 public RawImage rawImage; 10 bool isScreenShot = false; 11 12 void Update() 13 { 14 //将镜头的画面保存到本地 15 if (Input.GetKeyDown(KeyCode.Q)) 16 { 17 Texture2D tex = RenderTexture2Texture2D(camera.targetTexture); 18 19 //展示 20 rawImage.texture = tex; 21 22 //保存到本地 23 byte[] bytes = tex.EncodeToPNG(); 24 File.WriteAllBytes(Application.dataPath + "/RenderTexture/Test.png", bytes); 25 UnityEditor.AssetDatabase.Refresh(); 26 } 27 28 //屏幕截图(方法1) 29 if (Input.GetKeyDown(KeyCode.W)) 30 { 31 StartCoroutine(ScreenShotIEnumerator()); 32 } 33 34 //屏幕截图(方法2) 35 if (Input.GetKeyDown(KeyCode.E)) 36 { 37 isScreenShot = true; 38 } 39 } 40 41 public IEnumerator ScreenShotIEnumerator() 42 { 43 yield return new WaitForEndOfFrame(); 44 rawImage.texture = ScreenShot(); 45 } 46 47 private void OnPostRender() 48 { 49 //Debug.Log("OnPostRender"); 50 if (isScreenShot) 51 { 52 isScreenShot = false; 53 rawImage.texture = ScreenShot(); 54 } 55 } 56 57 //屏幕截图 58 public Texture2D ScreenShot() 59 { 60 Texture2D tex = new Texture2D(Screen.width, Screen.height, TextureFormat.ARGB32, false); 61 tex.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0); 62 tex.Apply(); 63 return tex; 64 } 65 66 //RenderTexture转Texture2D 67 public Texture2D RenderTexture2Texture2D(RenderTexture rt) 68 { 69 RenderTexture preRT = RenderTexture.active; 70 RenderTexture.active = rt; 71 Texture2D tex = new Texture2D(rt.width, rt.height, TextureFormat.ARGB32, false); 72 tex.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0); 73 tex.Apply(); 74 RenderTexture.active = preRT; 75 return tex; 76 } 77 }
以上是关于[Unity基础]RenderTexture的主要内容,如果未能解决你的问题,请参考以下文章