已知到可以创建一个RenderTexture赋值给Camera后,就可以将这个Camera渲染的内容填充到这个RenderTexture中了。但是这是针对某个相机的,如果是要显示多个相机的,就不能这样子做了,办法就是在层次较高的相机上加上后处理方法OnRenderImage,然后将source(RenderTexture)转换为Texture2D,然后赋值给用来显示的UITexture就可以了。为什么不直接把source直接赋值给UITexture,因为我试过了,Editor上是正常的,到手机上就会显示所有相机渲染后的内容,然后就会产生镜像的叠加。
using System.Collections;
using UnityEngine;
public class CreateMJShareTex : MonoBehaviour {
public UITexture tex;
private bool isTurnTexture = false;
private void OnEnable()
{
StartCoroutine(WaitOne());
}
IEnumerator WaitOne()
{
yield return new WaitForEndOfFrame();
isTurnTexture = true;
}
private void OnRenderImage(RenderTexture source, RenderTexture destination)
{
if (isTurnTexture)
{
RenderTexture curTex = RenderTexture.active;
Texture2D tex2d = new Texture2D(source.width, source.height);
RenderTexture.active = source;
tex2d.ReadPixels(new Rect(0, 0, source.width, source.height), 0, 0);
tex2d.Apply();
RenderTexture.active = curTex;
tex.mainTexture = tex2d;
isTurnTexture = false;
}
Graphics.Blit(source, destination);
}
}