使用RenderTexture实现3D模型与UI的组合显示

  • 引言
    游戏中常见的功能如角色创建选择,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.
    官方的说辞:还可以实现视频监视器, 监控显示器,反射等。

参考:
渲染纹理 Render Texture
Unity3D RenderTexture实现3D立绘
Camera

猜你喜欢

转载自blog.csdn.net/u010832643/article/details/73351050
今日推荐