33. RenderTarget

1.RenderTarget简介

2.RenderTarget示例

3.RenderTarget要点


1.RenderTarget简介

csharp 复制代码
RenderTarget(简称RT, 渲染目标)本质是"显存中的一块缓冲区/虚拟画布"

默认情况下, Unity的相机直接把画面渲染到"屏幕缓冲区", 而RenderTarget允许你让相机把画面渲染到这块"虚拟画布",而

非直接显示, 这块画布的具体实现是Unity的"RenderTexture"类; 渲染完成后, 可以将它作为纹理采样, 二次处理或最终再

渲染到屏幕上

简单类比:正常画画是直接画在最终展示的画布(屏幕)上, 而RenderTarget是先画在草稿纸(虚拟画布)上, 修改/合成后再复

制到最终画布

2.RenderTarget示例

csharp 复制代码
using UnityEngine;

public class RenderTargetDemo : MonoBehaviour
{
    // 用于渲染到RT的相机(需在场景中指定)
    public Camera renderCamera;
    // 显示RT内容的平面(挂MeshRenderer组件)
    public GameObject displayPlane;
    // 动态创建的RenderTarget(RenderTexture)
    private RenderTexture _renderTarget;

    void Start()
    {
        // 1. 创建RenderTarget(核心参数:分辨率、深度缓冲区、纹理格式)
        // 分辨率:1024x1024足够,过高会增加显存占用;深度缓冲区24=标准值(支持深度测试)
        _renderTarget = new RenderTexture(1024, 1024, 24, RenderTextureFormat.ARGB32);
        // 可选:开启4倍抗锯齿(MSAA),注意显存消耗
        _renderTarget.antiAliasing = 4;
        // 标记为临时资源,方便Unity管理(仍需手动释放)
        _renderTarget.hideFlags = HideFlags.HideAndDontSave;

        // 2. 让相机渲染到RT(而非屏幕)
        renderCamera.targetTexture = _renderTarget;
        // 关闭相机的屏幕显示(只渲染到RT)
        renderCamera.enabled = true;

        // 3. 将RT赋值给平面材质,显示RT内容
        if (displayPlane != null && displayPlane.TryGetComponent(out MeshRenderer planeMr))
        {
            Material planeMat = planeMr.material;
            planeMat.mainTexture = _renderTarget; // RT作为材质纹理
        }
    }

    // 关键:销毁时释放RT,避免显存泄漏(新手最易踩坑)
    void OnDestroy()
    {
        if (_renderTarget != null)
        {
            RenderTexture.ReleaseTemporary(_renderTarget); // 释放显存资源
            _renderTarget = null;
        }
        // 恢复相机默认渲染到屏幕(可选)
        if (renderCamera != null)
        {
            renderCamera.targetTexture = null;
        }
    }
}
csharp 复制代码
a.RenderTexture构造参数: 宽度/高度决定RT分辨率(1024x1024的ARGB32格式RT约占4MB显存), 深度缓冲区设为0则无法处

理物体遮挡

b.camera.targetTexture: 这是使用RT的核心设置, 将相机输出重定向到RT

c.RenderTexture.ReleaseTemporary: 必须手动释放RT资源, 否则频繁创建会导致显存泄漏, 最终触发内存溢出

3.RenderTarget要点

csharp 复制代码
a.控制RT分辨率: 不要无脑用4KRT, 比如镜面反射用512x512、小地图用256x256足够, 分辨率减半, 显存占用减少75%

b.选择轻量化格式

- 普通渲染用ARGB32(4字节/像素)

- 仅需亮度信息用R8(1字节/像素)

- 高精度特效(HDR)用RGBAHalf(8字节/像素), 避免过度使用

c.复用 RT: 创建全局RT池, 重复使用同一RT, 避免每帧创建/销毁(显存分配开销极大)

d.关闭无用功能: 不需要深度测试的RT, 比如: UI渲染, 将深度缓冲区设为0; 不需要抗锯齿的RT, 关闭MSAA
相关推荐
是果果呀儿15 分钟前
Vuforia实现物体旋转、移动、缩放
unity·增强现实
不知名的老吴3 小时前
Unity3D 2022安装教程及全流程下载步骤指南
unity·游戏引擎
Thomas_YXQ3 小时前
Unity3D Addressable 深度优化热更性能消耗
开发语言·3d·unity·微信
程序员也有头发3 小时前
如何使用AI工具开发Unity
unity·游戏引擎·ai编程
隔窗听雨眠4 小时前
从零开始的游戏开发入门指南
unity
sinat_384503114 小时前
【无标题】
unity·webgl
隔窗听雨眠5 小时前
Unity与Simulink联合仿真:实现无人机目标追踪系统
unity·无人机·cocos2d·simulink
winlife_5 小时前
全程用 AI 做一款商业级手游 · EP10 道具系统:让三个按钮真正改变棋盘
windows·算法·unity·ai编程·游戏开发·mcp·玩法系统
游乐码20 小时前
Unity基础(十二)资源异步加载
unity·游戏引擎
weixin_4242946721 小时前
程序不知道写在了什么位置???
unity