使用RenderTexture实现3D模型与UI的组合显示
发表于2018-12-13
游戏中常见的功能如角色创建选择,NPC对话等功能中,需要3D模型与UI的组合显示,该如何实现呢?








如何实现
首先想到添加一个3D camera将3D模型画出来,利用Camera中的Target Texture属性来缓存绘制的3D形象,再设置相应的位置,旋转等属性。
实现环境
利用NGUI\Examples\Scenes\Example X - Character的场景来进行实验。
原生运行状态:

1.在2D UIPanel下创建UITexture组件用来显示缓存的renderTexture

2.创建一个3D camera用以缓存Target Texture

源代码
3.缓存TargetTexture,设置Texture。
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CombineTexture : MonoBehaviour { [SerializeField] private Camera _cam; private RenderTexture _tex; void OnGUI() { if (GUI.Button(new Rect(100f, 100f, 100f, 50f), "Combine Texture")) { _tex = new RenderTexture(500, 500, 16); // 创建临时变量RenderTexture缓存Target Texture if (_cam != null) { _cam.targetTexture = _tex; } gameObject.GetComponent<UITexture>().mainTexture = _tex; // 设置UITexture的Texture属性 } } void OnDisable() { // 释放资源 if (_cam != null) _cam.targetTexture = null; gameObject.GetComponent<UITexture>().mainTexture = null; Destroy(_tex); _tex = null; } }
运行结果

在右侧的小窗口内会有一个动态的模型,与屏幕中间的模型同步显示。
注意点
在NGUI中一个UITexture对应一个drawcall,要做好对UITexture的管理;
如果要实现快照,对模型的截图等需求时,只需将RenderTexture的某一帧保存即可;
还能做什么
Render Texture
This will place the camera’s view onto a Texture that can then be applied to another object. This makes it easy to create sports arena video monitors, surveillance cameras, reflections etc.
官方的说辞:还可以实现视频监视器, 监控显示器,反射等。