每次构建项目时,Unity 编辑器都会编译构建所需的所有着色器:针对每个所需的图形 API 编译每个所需的着色器变体。
当您在 Unity 编辑器中工作时,编辑器不会提前编译所有内容。这是因为为每个图形 API 编译每个变体可能需要很长时间。
相反,Unity 编辑器会这样做:
Library/ShaderCache
文件夹。着色器编译使用名为 UnityShaderCompiler
的进程。可启动多个 UnityShaderCompiler
编译器进程(通常在机器中每个 CPU 核心对应一个),这样在播放器构建时就可以并行完成着色器编译。当编辑器不编译着色器时,编译器进程不执行任何操作,也不消耗计算机资源。
如果有许多经常更改的着色器,着色器缓存文件夹可能会变得非常大。删除此文件夹是安全的;只会导致 Unity 重新编译着色器变体。
在播放器构建时,所有“尚未编译”的着色器变体都将被编译,因此即使编辑器不会使用这些着色器变体,它们也会存在于游戏数据中。
不同平台使用不同的着色器编译器来编译着色器程序,如下所述:
使用 pragma 指令可以配置各种着色器编译器设置。
Shader compilation involves several steps. One of the first steps is preprocessing. During this step, a program called a preprocessor prepares the shader source code for the compiler.
In previous versions of Unity, the Editor used the preprocessor provided by the shader compiler for the current platform. Now, you can choose whether to use Unity’s Caching Shader Preprocessor, or revert to the previous behavior. Unless you experience problems, you should use the Caching Shader Preprocessor.
The Caching Shader Preprocessor is optimized for faster shader import and compilation; it is up to 25% faster. It works by caching intermediate preprocessing data, so the Editor only needs to parse include files when their contents change. This makes compiling multiple variants of the same shader more efficient. Enabling the Caching Shader Preprocessor has the most noticeable effect when shaders within a project use a large set of common include files.
As well as improved performance, the Caching Shader Preprocessor adds the following features:
#pragma
directives inside conditionals.#pragma warning
directive.#include_with_pragmas
directive, which allows you to put #pragma
directives in include files.For detailed information on the differences between the Caching Shader Preprocessor and the previous behavior, see the Unity forum: New shader preprocessor.
You can enable or disable the Caching Shader Preprocessor with the Caching Shader Preprocessor checkbox in the Shader Compilation section of the Editor settings window, or with the EditorSettings.cachingShaderPreprocessor API.
在构建游戏时,Unity 可能检测到游戏不使用某些内部着色器变体,并从构建数据中排除(“剥离”)它们。构建时剥离将用于以下各项:
#pragma shader_feature
的着色器,Unity 会自动检查是否使用了变体。如果构建中的材质都不使用某个变体,则该变体不会包含在构建中。请参阅内部着色器变体文档。标准着色器会使用此功能。上述的组合通常会大大减小着色器数据大小。例如,完全编译后的标准着色器将占用几百兆字节,但在典型的项目中,通常最终仅占用几兆字节(并且通常会由应用程序打包过程进一步压缩)。