Version: 2019.4
GLSL Shader programs
Shader Compilation Target Levels

Shading language used in Unity

In Unity, you write shader programs using the HLSL programming language.

Unity originally used the Cg language, hence the name of some of Unity’s shader keywords (CGPROGRAM) and file extensions (.cginc). Unity no longer uses Cg, but these keywords and file extensions are still supported. Note that all shader program code must be valid HLSL, even if it uses the Cg-related keywords and file extensions.

The only difference between using HLSLPROGRAM and CGPROGRAM is in the files that Unity automatically includes when it compiles the shader program. This is for backwards compatibility reasons. For more information, see Built-in shader include files.

HLSL syntax

The HLSL language itself has two syntaxes: a “legacy” DX9-style syntax, and a more modern DX10+ style syntax.

The difference is mostly in how texture sampling functions work:

  • The legacy syntax uses sampler2D, tex2D() and similar functions. This syntax works on all platforms.
  • The DX10+ syntax uses Texture2D, SamplerState and .Sample() functions. Some forms of this syntax do not work on OpenGL platforms, due to how textures and samplers are not different objects in OpenGL.

In Unity, you can avoid problems with HLSL syntax platform support by using predefined macros to declare and sample textures. Unity expands these macros to the most appropriate syntax, depending on the platform that the shader is being compiled for.

Shader compilers

Different platforms use different shader compilers for shader program compilation as follows:

  • Windows and Microsoft platforms (DX11, DX12 and Xbox One) all use Microsoft’s HLSL compiler (currently FXC / D3DCompiler_47).
  • OpenGL (Core & ES), Metal and Vulkan use Microsoft’s HLSL followed by bytecode translation into GLSL, Metal or SPIR-V, using HLSLcc.
  • Other console platforms use their respective compilers (e.g. PSSL on PS4).
  • Surface Shaders use HLSL and MojoShader for code generation analysis step.

You can use predefined shader macros to identify which compiler Unity is using, for instance to use HLSL syntax only supported by one compiler, or to work around a compiler bug.

Смотрите так же

GLSL Shader programs
Shader Compilation Target Levels
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961