Reuse HLSL code
Include or duplicate HLSL in different places, or share pragma directives across different shaders.
Read time 2 minutesLast updated a month ago
To tell the compiler to include existing High-Level Shader Language (HLSL) code in another file or section, use the following methods:
- Include an HLSL file in another, using the standard HLSL directive.
#include - Duplicate HLSL in multiple places using the and
HLSLINCLUDEmacros.ENDHLSL - Apply a directive to multiple HLSL files, using the Unity
#pragmadirective.#include_with_pragmas
Include an HLSL file in another
Unity supports the standard HLSL directive. For more information, refer to include directive in the Microsoft HLSL documentation.
#includeDuplicate HLSL in multiple places
To duplicate HLSL code in all the sections of your code, for example to add the same variables in multiple blocks, wrap the code you want to reuse in and macros. Unity adds the code at the top of every block.
PassHLSLINCLUDEENDHLSLHLSLPROGRAMFor example:
Shader "Examples/ExampleShader"{ HLSLINCLUDE // Add HLSL code you want to share across the file. ENDHLSL SubShader { Pass { ... HLSLPROGRAM // Unity pastes the contents of the HLSLINCLUDE block here. ENDHLSL } Pass { ... HLSLPROGRAM // Unity pastes the contents of the HLSLINCLUDE block here. ENDHLSL } }}
Apply a pragma directive to multiple files
To apply a directive to multiple shader files, use the Unity directive.
#pragma#include_with_pragmasYou can use this method to add an argument in multiple files, but toggle the arguments on and off by updating only one file. For example, you can create and toggle a debugging keyword that enables and disables conditional debugging code in multiple shaders.
- Add a directive to a separate shader file. For example, create a one-line HLSL file with a pragma that enables shader debug symbols:
#pragma
#pragma enable_debug_symbols
- In each shader you want to include the directive in, add an directive to include the file. For example:
#include_with_pragmas
#include_with_pragmas "path-to-include-file"