使用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

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值