Version: Unity 6.0 (6000.0)
语言 : 中文
异步着色器编译简介
检测异步着色器编译

启用或禁用异步着色器编译

默认情况下已启用异步着色器编译。

要利用或禁用异步着色器编译,请执行以下操作:

  1. 选择__编辑 (Edit) > 项目设置 (Project Settings) > 编辑器 (Editor)__。
  2. 在编辑器设置底部的__着色器编译 (Shader Compilation)__ 下,取消选中__异步着色器编译 (Asynchronous Shader Compilation)__ 复选框。

注意:默认情况下,以这种方式启用和禁用异步着色器编译仅影响场景和游戏视图。如果希望将此功能用于编辑器的其他部分,请参阅自定义编辑器工具和异步着色器编译

为特定渲染调用启用和禁用异步着色器编译

您可以在 C# 脚本中为特定渲染命令启用或禁用异步着色器编译。

以下说明展示了如何在直接作用域和 CommandBuffer 作用域中启用或禁用该功能。

在直接作用域中

在直接作用域中,您可以使用 ShaderUtil.allowAsyncCompilation

为此需要执行以下操作:

  1. 将当前 ShaderUtil.allowAsyncCompilation 状态存储在变量中。
  2. 调用渲染命令之前,将 ShaderUtil.allowAsyncCompilation 设为 false
  3. 调用渲染命令。
  4. 调用渲染命令后,将 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 作用域中

CommandBuffer 作用域中,可以使用 ShaderUtil.SetAsyncCompilationShaderUtil.RestoreAsyncCompilation

  1. 在调用渲染命令之前,立即调用 ShaderUtil.SetAsyncCompilation,并将其设置为 false。CommandBuffer 中的后续命令不允许异步编译。
  2. 将渲染命令添加到 CommandBuffer。
  3. 在渲染命令之后,调用 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 对象在渲染开始时始终存在且编译速度相对较快,这是一个很好的选择。如果您正在执行高级渲染,很可能需要这样做。

要为特定 Shader 对象强制进行同步编译,请将 #pragma editor_sync_compilation指令添加到您的着色器源代码中。

注意:对于在渲染过程中会遇到新变体的复杂 Shader 对象,不要强制进行同步编译;这种情况下会使编辑器中的渲染卡顿。

自定义编辑器工具和异步着色器编译

默认情况下,异步着色器编译功能在游戏视图和场景视图中有效。如果要在自定义编辑器工具中使用该功能,可以通过 C# 为自定义工具启用该功能。

为此,您可以为特定的渲染调用启用异步着色器编译

异步着色器编译简介
检测异步着色器编译