unity-shaders-rendering

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Unity Shaders and Rendering

Unity 着色器与渲染

Overview

概述

Reference for Unity's rendering systems, shader development, lighting configuration, and visual effects. Covers all three render pipelines, Shader Graph, hand-written shaders, and VFX Graph.
Unity渲染系统、着色器开发、光照配置及视觉效果参考指南。涵盖三种渲染管线、Shader Graph、手写着色器及VFX Graph。

Render Pipeline Comparison

渲染管线对比

FeatureBuilt-in RPURPHDRP
TargetLegacy projectsMobile, VR, wide rangeHigh-end PC/console
Shader languageSurface shaders + HLSLHLSL (no surface shaders)HLSL
Shader GraphYesYesYes
SRP BatcherNoYesYes
Render FeaturesNoYes (ScriptableRendererFeature)Custom Pass
Post-processingPost Processing Stack v2Volume system (built-in)Volume system (built-in)
Ray tracingNoNo (probe-based)Yes (DXR)
PerformanceModerateOptimized for scaleHighest fidelity
Recommendation: Use URP for new projects unless targeting high-end visuals exclusively (HDRP). Built-in RP is legacy -- migrate when possible.
特性内置管线(Built-in RP)URPHDRP
目标场景遗留项目移动端、VR及广泛场景高端PC/主机
着色器语言Surface着色器 + HLSLHLSL(无Surface着色器)HLSL
Shader Graph支持
SRP批处理
渲染功能是(ScriptableRendererFeature)自定义通道(Custom Pass)
后处理Post Processing Stack v2内置Volume系统内置Volume系统
光线追踪否(基于探针)是(DXR)
性能表现中等针对规模化场景优化最高画质
建议: 新项目优先使用URP,除非专门针对高端视觉效果选择HDRP。内置管线已属遗留技术,建议尽可能迁移。

Shader Graph

Shader Graph

Getting Started

入门指南

  1. Right-click in Project: Create > Shader Graph > URP > Lit Shader Graph
  2. Double-click to open Shader Graph editor
  3. Build node network connecting to Master Stack outputs
  4. Create a Material using the shader, assign to renderers
  1. 在项目窗口右键:创建 > Shader Graph > URP > 光照着色器图(Lit Shader Graph)
  2. 双击打开Shader Graph编辑器
  3. 构建节点网络并连接至主栈输出
  4. 使用该着色器创建材质,分配给渲染器

Master Stack Outputs (URP Lit)

URP光照主栈输出

OutputTypePurpose
Base ColorColor (RGB)Albedo/diffuse color
NormalVector3Tangent-space normal map
MetallicFloat (0-1)Metal vs. dielectric
SmoothnessFloat (0-1)Roughness inverse
EmissionColor (RGB)Self-illumination
AlphaFloat (0-1)Transparency
Alpha Clip ThresholdFloatCutoff for alpha testing
输出项类型用途
基础颜色(Base Color)颜色(RGB)反照率/漫反射颜色
法线(Normal)向量3(Vector3)切线空间法线贴图
金属度(Metallic)浮点数(0-1)金属材质 vs 绝缘材质
光滑度(Smoothness)浮点数(0-1)粗糙度的倒数
自发光(Emission)颜色(RGB)自发光效果
透明度(Alpha)浮点数(0-1)透明度
Alpha裁剪阈值(Alpha Clip Threshold)浮点数Alpha测试的截断值

Common Node Patterns

常见节点模式

EffectKey Nodes
DissolveNoise > Step > Alpha Clip + Edge emission
Scrolling UVTime > Multiply > Add to UV
Fresnel glowFresnel Effect > Multiply color > Emission
Triplanar mappingTriplanar node (avoids UV stretching)
Color shiftLerp between colors using parameter or time
Vertex displacementNoise > Multiply > Add to Position
OutlineTwo-pass: inverted hull in custom render feature
效果核心节点
溶解效果噪声(Noise)> 阶跃(Step)> Alpha裁剪 + 边缘自发光
UV滚动时间(Time)> 乘法(Multiply)> 叠加至UV
菲涅尔发光菲涅尔效果(Fresnel Effect)> 颜色乘法 > 自发光
三平面映射三平面节点(避免UV拉伸)
颜色偏移使用参数或时间在颜色间插值(Lerp)
顶点位移噪声(Noise)> 乘法(Multiply)> 叠加至位置(Position)
轮廓线双通道:在自定义渲染功能中使用反转外壳

Shader Graph Sub Graphs

Shader Graph子图

Extract reusable node groups into Sub Graphs (Create > Shader Graph > Sub Graph). Use for shared noise functions, UV transformations, or custom lighting models.
将可复用的节点组提取为子图(创建 > Shader Graph > 子图)。适用于共享噪声函数、UV变换或自定义光照模型。

Hand-Written Shaders (ShaderLab + HLSL)

手写着色器(ShaderLab + HLSL)

URP Shader Structure

URP着色器结构

hlsl
Shader "Custom/SimpleUnlit"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _Color ("Color", Color) = (1,1,1,1)
    }

    SubShader
    {
        Tags { "RenderType"="Opaque" "RenderPipeline"="UniversalPipeline" }

        Pass
        {
            HLSLPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"

            struct Attributes
            {
                float4 positionOS : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct Varyings
            {
                float4 positionHCS : SV_POSITION;
                float2 uv : TEXCOORD0;
            };

            TEXTURE2D(_MainTex);
            SAMPLER(sampler_MainTex);

            CBUFFER_START(UnityPerMaterial)
                float4 _MainTex_ST;
                half4 _Color;
            CBUFFER_END

            Varyings vert(Attributes IN)
            {
                Varyings OUT;
                OUT.positionHCS = TransformObjectToHClip(IN.positionOS.xyz);
                OUT.uv = TRANSFORM_TEX(IN.uv, _MainTex);
                return OUT;
            }

            half4 frag(Varyings IN) : SV_Target
            {
                half4 tex = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, IN.uv);
                return tex * _Color;
            }
            ENDHLSL
        }
    }
}
Key differences from Built-in shaders:
  • Use
    HLSLPROGRAM
    /
    ENDHLSL
    (not
    CGPROGRAM
    /
    ENDCG
    )
  • Include URP shader library, not UnityCG.cginc
  • Use
    TEXTURE2D
    /
    SAMPLER
    macros (not
    sampler2D
    )
  • Wrap properties in
    CBUFFER_START(UnityPerMaterial)
    for SRP Batcher compatibility
hlsl
Shader "Custom/SimpleUnlit"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _Color ("Color", Color) = (1,1,1,1)
    }

    SubShader
    {
        Tags { "RenderType"="Opaque" "RenderPipeline"="UniversalPipeline" }

        Pass
        {
            HLSLPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"

            struct Attributes
            {
                float4 positionOS : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct Varyings
            {
                float4 positionHCS : SV_POSITION;
                float2 uv : TEXCOORD0;
            };

            TEXTURE2D(_MainTex);
            SAMPLER(sampler_MainTex);

            CBUFFER_START(UnityPerMaterial)
                float4 _MainTex_ST;
                half4 _Color;
            CBUFFER_END

            Varyings vert(Attributes IN)
            {
                Varyings OUT;
                OUT.positionHCS = TransformObjectToHClip(IN.positionOS.xyz);
                OUT.uv = TRANSFORM_TEX(IN.uv, _MainTex);
                return OUT;
            }

            half4 frag(Varyings IN) : SV_Target
            {
                half4 tex = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, IN.uv);
                return tex * _Color;
            }
            ENDHLSL
        }
    }
}
与内置着色器的主要差异:
  • 使用
    HLSLPROGRAM
    /
    ENDHLSL
    (而非
    CGPROGRAM
    /
    ENDCG
  • 引入URP着色器库,而非UnityCG.cginc
  • 使用
    TEXTURE2D
    /
    SAMPLER
    宏(而非
    sampler2D
  • 将属性包裹在
    CBUFFER_START(UnityPerMaterial)
    中,以兼容SRP批处理

Lighting

光照

Light Types

光照类型

TypeUse ForShadow Cost
DirectionalSun, global illuminationLow (cascaded shadow maps)
PointTorches, lampsMedium
SpotFlashlights, stage lightsMedium
Area (baked only)Soft window light, panelsHigh (bake only)
类型适用场景阴影开销
方向光太阳、全局光照低(级联阴影贴图)
点光源火把、灯具
聚光灯手电筒、舞台灯光
区域光(仅烘焙)柔和窗户光、面板光高(仅烘焙)

Lighting Modes

光照模式

ModeDescriptionBest For
RealtimeComputed every frameDynamic objects, few lights
BakedPre-computed into lightmapsStatic environments
MixedBaked indirect + realtime directBest balance
模式描述最佳适用场景
实时每帧计算动态物体、少量光源
烘焙预计算至光照贴图静态场景
混合烘焙间接光照 + 实时直接光照最佳平衡方案

Lightmap Baking Tips

光照贴图烘焙技巧

  • Set lightmap resolution based on scene scale (10-40 texels/unit for indoor)
  • Use Light Probes for dynamic objects in baked scenes
  • Use Reflection Probes for metallic/reflective surfaces
  • Enable GPU Lightmapper for faster bake times
  • Mark objects as Contribute GI in the Static flags
  • 根据场景比例设置光照贴图分辨率(室内场景建议10-40 texels/单位)
  • 在烘焙场景中为动态物体使用光照探针(Light Probes)
  • 为金属/反光表面使用反射探针(Reflection Probes)
  • 启用GPU光照贴图器以加快烘焙速度
  • 在静态标记中设置物体为"贡献GI(Contribute GI)"

Post-Processing (Volume System)

后处理(Volume系统)

text
Setup:
1. Add a Volume (Global or Local) to the scene
2. Create a Volume Profile asset
3. Add overrides: Bloom, Color Adjustments, Tonemapping, etc.
4. Camera must have Post Processing enabled (URP Camera settings)
EffectPerformanceNotes
BloomLowUse threshold to control intensity
Color AdjustmentsVery LowSaturation, contrast, color filter
TonemappingVery LowACES for cinematic look
VignetteVery LowFrame darkening
Ambient Occlusion (SSAO)MediumDisable on mobile
Depth of FieldHighUse Bokeh only for cinematics
Motion BlurMediumCan cause motion sickness in VR
text
设置步骤:
1. 向场景添加Volume(全局或局部)
2. 创建Volume Profile资源
3. 添加覆盖效果:Bloom、颜色调整、色调映射等
4. 相机需启用后处理(URP相机设置)
效果性能开销说明
Bloom使用阈值控制强度
颜色调整极低饱和度、对比度、颜色滤镜
色调映射极低使用ACES实现电影级效果
暗角极低画面边缘暗化
环境光遮蔽(SSAO)移动端建议禁用
景深仅在影视化场景中使用散景效果
运动模糊VR场景中可能引发晕动症

VFX Graph vs Particle System

VFX Graph vs 粒子系统

FeatureParticle System (Shuriken)VFX Graph
ExecutionCPUGPU (compute shader)
Particle countThousandsMillions
ComplexityComponent-based, simpleNode-based, complex
PlatformAllCompute shader capable only
IntegrationPhysics, collisionLimited physics
Use Particle System for gameplay-integrated effects (physics collisions, small counts). Use VFX Graph for visual spectacles (rain, fire, magic, ambient particles).
特性粒子系统(Shuriken)VFX Graph
执行方式CPUGPU(计算着色器)
粒子数量数千级数百万级
复杂度组件化、简单节点化、复杂
支持平台所有平台仅支持具备计算着色器能力的平台
集成度物理、碰撞物理集成有限
粒子系统适用于与游戏玩法集成的效果(物理碰撞、少量粒子)。VFX Graph适用于视觉奇观(雨、火、魔法、环境粒子)。

URP Render Features

URP渲染功能

Extend URP rendering with custom ScriptableRendererFeatures:
csharp
public class OutlineFeature : ScriptableRendererFeature
{
    OutlinePass _pass;

    public override void Create()
    {
        _pass = new OutlinePass();
        _pass.renderPassEvent = RenderPassEvent.AfterRenderingOpaques;
    }

    public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingData data)
    {
        renderer.EnqueuePass(_pass);
    }
}
Common uses: custom outlines, screen-space effects, render texture generation, stencil-based effects.
通过自定义ScriptableRendererFeature扩展URP渲染:
csharp
public class OutlineFeature : ScriptableRendererFeature
{
    OutlinePass _pass;

    public override void Create()
    {
        _pass = new OutlinePass();
        _pass.renderPassEvent = RenderPassEvent.AfterRenderingOpaques;
    }

    public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingData data)
    {
        renderer.EnqueuePass(_pass);
    }
}
常见用途:自定义轮廓线、屏幕空间效果、渲染纹理生成、基于模板的效果。

Additional Resources

额外资源

Reference Files

参考文件

  • references/shader-recipes.md
    -- Complete shader implementations: toon/cel shading, water, dissolve, hologram, force field, procedural skybox, stencil portal, vertex animation, custom lighting models
  • references/lighting-vfx-detail.md
    -- Advanced lighting setups, GI troubleshooting, VFX Graph cookbook (fire, smoke, electricity, portals), Scriptable Render Pipeline customization, custom render passes
  • references/shader-recipes.md
    -- 完整着色器实现:卡通着色、水效果、溶解、全息图、力场、程序化天空盒、模板传送门、顶点动画、自定义光照模型
  • references/lighting-vfx-detail.md
    -- 高级光照设置、GI故障排查、VFX Graph食谱(火焰、烟雾、电流、传送门)、可脚本化渲染管线定制、自定义渲染通道