默认情况下已启用异步着色器编译。
要利用或禁用异步着色器编译,请执行以下操作:
注意:默认情况下,以这种方式启用和禁用异步着色器编译仅影响场景和游戏视图。如果希望将此功能用于编辑器的其他部分,请参阅自定义编辑器工具和异步着色器编译。
您可以在 C# 脚本中为特定渲染命令启用或禁用异步着色器编译。
以下说明展示了如何在直接作用域和 CommandBuffer 作用域中启用或禁用该功能。
在直接作用域中,您可以使用 ShaderUtil.allowAsyncCompilation。
为此需要执行以下操作:
ShaderUtil.allowAsyncCompilation 状态存储在变量中。ShaderUtil.allowAsyncCompilation 设为 false。ShaderUtil.allowAsyncCompilation 恢复到之前的状态。下面是一个伪代码示例:
// Store the current state
bool oldState = ShaderUtil.allowAsyncCompilation;
// Disable async compilation
ShaderUtil.allowAsyncCompilation = false;
// Enter your rendering code that should never use the placeholder shader, for example UI elements or characters.
Graphics.RenderMesh(...);
// Restore the old state
ShaderUtil.allowAsyncCompilation = oldState;
在 CommandBuffer 作用域中,可以使用 ShaderUtil.SetAsyncCompilation 和 ShaderUtil.RestoreAsyncCompilation。
ShaderUtil.SetAsyncCompilation,并将其设置为 false。CommandBuffer 中的后续命令不允许异步编译。Shader.Util.RestoreAsyncCompilation 以恢复异步着色器编译的状态。下面是一个示例:
// Create the CommandBuffer
CommandBuffer cmd = new CommandBuffer();
// Disable async compilation for subsequent commands
ShaderUtil.SetAsyncCompilation(cmd, false);
/// Enter your rendering commands that should never use the placeholder shader, for example UI elements or characters.
cmd.DrawMesh(...);
// Restore the old state
ShaderUtil.RestoreAsyncCompilation(cmd);
通过强制编辑器始终进行同步编译,您可以为特定 Shader 对象禁用异步着色器编译。如果生成数据的 Shader 对象在渲染开始时始终存在且编译速度相对较快,这是一个很好的选择。如果您正在执行高级渲染,很可能需要这样做。
要为特定 Shader 对象强制进行同步编译,请将 #pragma editor_sync_compilation指令添加到您的着色器源代码中。
注意:对于在渲染过程中会遇到新变体的复杂 Shader 对象,不要强制进行同步编译;这种情况下会使编辑器中的渲染卡顿。
默认情况下,异步着色器编译功能在游戏视图和场景视图中有效。如果要在自定义编辑器工具中使用该功能,可以通过 C# 为自定义工具启用该功能。
为此,您可以为特定的渲染调用启用异步着色器编译。