> For the complete documentation index, see [llms.txt](https://docs.convai.com/api-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/character-actions/dispatcher-and-batch-policies.md).

# 分发器和批处理策略

配置分发器的批处理策略、失败策略、语音门控超时、插话和生命周期事件，以用于角色动作执行。

`ConvaiActionDispatcher` 是动作系统的运行时执行层。它会监听来自 Convai 的命令批次，根据当前会话的配置解析每个动作及其目标，并逐步调用绑定的执行器组件。两个策略分别控制执行期间收到新批次时的处理方式，以及某个步骤失败时的处理方式。语音门控还可以让新批次的第一个动作等到角色开始说话后再执行；此外，玩家开始说话时，分发器也可以选择取消自身正在执行的工作。

### 组件概览

| 属性       | 值                                                                |
| -------- | ---------------------------------------------------------------- |
| **菜单路径** | `Add Component → Convai → Convai Action Runner`                  |
| **命名空间** | `Convai.Runtime.Actions`                                         |
| **约束**   | `DisallowMultipleComponent`, `RequireComponent(ConvaiCharacter)` |

分发器必须与 `GameObject` 位于同一对象上， `ConvaiCharacter`也是如此。每个角色只能有一个分发器。在 Actions Editor 的 **Character Settings** 选项卡中，此组件显示为 **Convai Action Runner** ，位于 **Actions Are Run By** 下方 — 请参阅 [配置角色动作](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/character-actions/configuring-actions.md#where-action-behaviors-live).

### Inspector 字段

| 字段                            | 类型                                 | 默认值         | 说明                                                                                                                          |
| ----------------------------- | ---------------------------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------- |
| `_batchPolicy`                | `ConvaiActionBatchPolicy`          | `Queue`     | 另一个批次正在执行时，如何处理传入的批次                                                                                                        |
| `_failurePolicy`              | `ConvaiActionBatchFailurePolicy`   | `StopBatch` | 步骤失败时，是中止批次中剩余的步骤，还是继续执行                                                                                                    |
| `_speechGateTimeoutSeconds`   | `float`                            | `2`         | 新批次的第一个动作在角色开始说话前最多等待的秒数；超过此时间后仍会执行                                                                                         |
| `_defaultStepTimeoutSeconds`  | `float`                            | `60`        | 动作运行超时并被报告为超时之前允许的最长时间，仅在动作自身的 `TimeoutSeconds` 为 `0`时使用。若动作设置了自己的超时时间，则始终以该设置为准。 `0` 则会完全移除此安全限制。                          |
| `_cancelOnUserSpeech`         | `bool`                             | `false`     | 启用后，玩家开始说话会取消正在执行的批次并清空队列 — 效果与 `ReplaceCurrent`相同，只不过触发方是玩家，而不是新的后端批次。                                                     |
| `_enablePerformanceReactions` | `bool`                             | `true`      | 启用后，会在批次和步骤生命周期中通知注册在角色具身上下文中的所有 `IActionPerformanceReactor` 同伴（凝视：看向动作目标；肢体语言：点头回应；情绪：根据结果呈现情绪变化）。如果不存在具身上下文或反应器，则不执行任何操作。 |
| `_onBatchStarted`             | `UnityEvent`                       | —           | 批次开始执行时触发                                                                                                                   |
| `_onStepStarted`              | `ConvaiActionInvocationUnityEvent` | —           | 在每个步骤开始时触发                                                                                                                  |
| `_onStepSucceeded`            | `ConvaiActionInvocationUnityEvent` | —           | 步骤执行器返回时触发 `Succeeded`                                                                                                      |
| `_onStepFailed`               | `ConvaiActionInvocationUnityEvent` | —           | 步骤因任何原因失败时触发                                                                                                                |
| `_onStepUnhandled`            | `ConvaiActionInvocationUnityEvent` | —           | 执行器返回时触发 `Unhandled`                                                                                                        |
| `_onStepCompleted`            | `ConvaiActionStepReportUnityEvent` | —           | 每个步骤在上述结果事件触发后触发一次，无论结果如何                                                                                                   |
| `_onBatchCompleted`           | `UnityEvent`                       | —           | 所有步骤均完成且未中止时触发                                                                                                              |
| `_onBatchAborted`             | `UnityEvent`                       | —           | 批次因失败策略而提前结束时触发                                                                                                             |

`ConvaiActionInvocationUnityEvent` 是一个可序列化的 `UnityEvent<ConvaiActionInvocation>`。在 Inspector 中将其连接起来，方式与标准 `UnityEvent` 完全相同 — 事件参数包含完整的调用上下文（操作名称、目标、角色、批次和步骤索引）。 `ConvaiActionStepReportUnityEvent` 是一个可序列化的 `UnityEvent<ConvaiActionStepReport>`通过公共 `OnStepCompleted` 属性公开 — 如果希望通过单个订阅点处理每个步骤的结果，而不是分别连接 `OnStepSucceeded`/`OnStepFailed`/`OnStepUnhandled` ，请使用此属性。

### 只读运行时状态

| 属性                  | 类型                               | 说明                               |
| ------------------- | -------------------------------- | -------------------------------- |
| `IsBusy`            | `bool`                           | 分发器当前是否正在运行批次。                   |
| `PendingBatchCount` | `int`                            | 当前正在运行的批次之后，等待处理的已接收批次数量。        |
| `CurrentActionName` | `string`                         | 当前正在运行的操作的显示名称；步骤之间为空。           |
| `BatchPolicy`       | `ConvaiActionBatchPolicy`        | 已配置的批次策略（代码中只读；在 Inspector 中设置）。 |
| `FailurePolicy`     | `ConvaiActionBatchFailurePolicy` | 已配置的失败策略（代码中只读；在 Inspector 中设置）。 |

`CancelOnUserSpeech` 和 `EnablePerformanceReactions` 是上述两个 Inspector 字段对应的可读写 C# 镜像 — 请参阅 [插话处理：用户说话时取消](#barge-in-cancel-on-user-speech).

### 批次策略

批次策略用于控制：当分发器仍在执行先前批次时，Convai 返回新的操作批次会发生什么。

| 策略               | 枚举值 | 行为                                                          |
| ---------------- | --- | ----------------------------------------------------------- |
| `Queue`          | `0` | 新批次会进入队列等待。当前批次完成后，才会启动下一个批次。适用于大多数场景。                      |
| `ReplaceCurrent` | `1` | 取消当前正在执行的步骤，并清空所有排队的批次。新批次立即开始。适用于需要中断的场景（例如：“停下，改为到这边来。”）。 |
| `DropIncoming`   | `2` | 在当前批次及所有排队批次完成之前，丢弃新批次。适用于不能中断进行中序列的场景（例如必须完整完成的安全演示）。      |

{% hint style="info" %}
`ReplaceCurrent` 通过 **取消当前正在运行的执行器步骤** 使用 `CancellationToken` ，并在启动新批次前清除所有待处理批次。要实现即时取消，执行器必须遵循取消令牌；请参阅 [编写自定义动作执行器](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/character-actions/writing-custom-executors.md).
{% endhint %}

### 失败策略

当执行器返回非成功结果（`Failed`, `Unhandled`, `Canceled`或 `TimedOut`).

| 策略              | 枚举值 | 行为                                              |
| --------------- | --- | ----------------------------------------------- |
| `StopBatch`     | `0` | 批次中的剩余步骤会被跳过。 `OnBatchAborted` 会触发。             |
| `ContinueBatch` | `1` | 无论步骤是否失败，都会继续执行下一步。 `OnBatchCompleted` 会在结束时触发。 |

当动作彼此独立时，使用 `ContinueBatch` ——“指向”失败不应妨碍后续的“点头或摇头”。对于有依赖关系的序列，使用 `StopBatch` （默认值）——“走到”失败时，应阻止后续需要角色已经到达的动作执行。

### 将首个动作设为等待角色说话后执行

Convai 可以标记某个动作，让分发器延迟执行，直到角色开始说话。两个字段控制此行为：一个由 Convai 在命令上设置，另一个可在匹配的动作定义中本地配置。

| 字段                           | 位置                       | 类型      | 默认值     | 说明                                                                 |
| ---------------------------- | ------------------------ | ------- | ------- | ------------------------------------------------------------------ |
| `WaitForBotSpeech`           | `ConvaiActionCommand`    | `bool`  | `false` | 由 Convai 在后端命令中设置。 `true` 会控制批次中的首个步骤，使其等待后再执行。                    |
| `DelayAfterBotSpeechSeconds` | `ConvaiActionCommand`    | `float` | `0`     | 等待条件解除后应用的额外延迟。仅当命令的 `WaitForBotSpeech` 为 `true`.                  |
| `WaitForBotSpeech`           | `ConvaiActionDefinition` | `bool`  | `false` | 在动作定义中本地配置的覆盖值。当其为 `true`.                                         |
| `DelayAfterBotSpeechSeconds` | `ConvaiActionDefinition` | `float` | `0`     | 等待条件解除后应用的额外延迟。仅当命令的 `WaitForBotSpeech` 为 `false` ，而定义中的值为 `true`. |

调度器仅在批次的第一步检查这些字段（`stepIndex == 0`）；同一批次中的后续步骤不会等待。当命令的 `WaitForBotSpeech` 或匹配定义中的 `WaitForBotSpeech` 值为 `true`时，会触发门控。当两者都不为 `true`时，该步骤将立即运行，不进行门控。

### 语音门控超时

`_speechGateTimeoutSeconds` 用于限制门控下第一步的等待时长，单位为秒。默认值为 `2`。此字段没有公开的 C# 属性，请在 Inspector 中设置。

门控开启期间，调度器会监听 `ConvaiCharacter.OnSpeechStarted`, `ConvaiCharacter.OnSpeechStopped`和 `ConvaiCharacter.OnTurnCompleted`。上述事件中最先触发的事件会释放门控；如果 `_speechGateTimeoutSeconds` 先到期，也会释放门控。 `OnStepStarted` 仅在门控释放后触发。

### 打断：用户说话时取消

启用 `_cancelOnUserSpeech` 后，玩家一开始说话，调度器便会取消正在执行的批次并清空队列——效果与 `ReplaceCurrent` 批次策略相同，但触发方是玩家，而不是新的后端批次。此功能默认关闭，因此在选择启用之前，现有场景不会发生变化。

该信号来自角色的具身上下文事件中心（Gaze 和 Body Language 已会响应的、基于服务器端 VAD 的 `PlayerSpeakingStateChanged` 信号）。如果角色未添加具身模块，打断功能会保持不活动状态，而不会抛出异常——调度器只会降级运行，不会失败。

```csharp
using Convai.Runtime.Actions;
using UnityEngine;

public sealed class BargeInFeedback : MonoBehaviour
{
    [SerializeField] private ConvaiActionDispatcher _dispatcher;

    private void OnEnable() => _dispatcher.OnCancelledByUserSpeech += HandleCancelled;
    private void OnDisable() => _dispatcher.OnCancelledByUserSpeech -= HandleCancelled;

    private void HandleCancelled(string interruptedAction) =>
        Debug.Log($"Barge-in cancelled: {interruptedAction}");
}
```

`OnCancelledByUserSpeech` 会携带被中断操作的显示名称；如果当时尚未开始执行任何操作，则携带空字符串。

### 生命周期事件

调度器会在批次和步骤执行的每个重要阶段触发事件。你可以通过 UnityEvent 字段在 Inspector 中订阅，也可以通过属性在 C# 中订阅。

#### 事件触发顺序

```
OnBatchStarted
  → OnStepStarted       （每个步骤都会触发）
  → OnStepSucceeded（如果执行器返回 Succeeded）
     或
  → OnStepFailed（如果执行器返回 Failed、Canceled 或 TimedOut）
     或
  → OnStepUnhandled（如果执行器返回 Unhandled）
  → OnStepCompleted（始终在上述结果事件之后触发，适用于每个步骤）
OnBatchCompleted（所有步骤均已完成，或 ContinueBatch 允许失败步骤继续执行）
  或
OnBatchAborted（StopBatch 策略在发生失败后提前终止批次）
```

#### 在 C# 中订阅

```csharp
using Convai.Runtime.Actions;
using UnityEngine;

public sealed class ActionFeedback : MonoBehaviour
{
    [SerializeField] private ConvaiActionDispatcher _dispatcher;

    private void OnEnable()
    {
        _dispatcher.OnBatchStarted.AddListener(HandleBatchStarted);
        _dispatcher.OnStepSucceeded.AddListener(HandleStepSucceeded);
        _dispatcher.OnStepFailed.AddListener(HandleStepFailed);
        _dispatcher.OnBatchCompleted.AddListener(HandleBatchCompleted);
        _dispatcher.OnBatchAborted.AddListener(HandleBatchAborted);
    }

    private void OnDisable()
    {
        _dispatcher.OnBatchStarted.RemoveListener(HandleBatchStarted);
        _dispatcher.OnStepSucceeded.RemoveListener(HandleStepSucceeded);
        _dispatcher.OnStepFailed.RemoveListener(HandleStepFailed);
        _dispatcher.OnBatchCompleted.RemoveListener(HandleBatchCompleted);
        _dispatcher.OnBatchAborted.RemoveListener(HandleBatchAborted);
    }

    private void HandleBatchStarted() => Debug.Log("Batch started");
    private void HandleStepSucceeded(ConvaiActionInvocation inv) =>
        Debug.Log($"Step succeeded: {inv.Command.Name}");
    private void HandleStepFailed(ConvaiActionInvocation inv) =>
        Debug.LogWarning($"Step failed: {inv.Command.Name}");
    private void HandleBatchCompleted() => Debug.Log("Batch completed");
    private void HandleBatchAborted() => Debug.LogWarning("Batch aborted");
}
```

### 手动注入批次

`EnqueueActions(IReadOnlyList<ConvaiActionCommand> actions)` 以编程方式向调度器提交一个批次，并遵循当前的批次和失败处理策略。可将其用于脚本化演示序列、自动化测试运行，或由游戏事件而非玩家语音触发的 NPC 行为。

```csharp
using System.Collections.Generic;
using Convai.Runtime.Actions;
using Convai.Shared.Types;
using UnityEngine;

public sealed class DemoTrigger : MonoBehaviour
{
    [SerializeField] private ConvaiActionDispatcher _dispatcher;

    public void RunSafetyDemo()
    {
        _dispatcher.EnqueueActions(new List<ConvaiActionCommand>
        {
            new ConvaiActionCommand("Walk To", "Extinguisher"),
            new ConvaiActionCommand("Point At", "Extinguisher"),
            new ConvaiActionCommand("Walk To", "Exit")
        });
    }
}
```

调度器会按顺序执行这些步骤。如果 `BatchPolicy` 为 `Queue`，此批次会排在任何正在执行的批次之后等待。现在，手动注入的批次会像后端批次一样经过相同的处理流程——清理线缆文本、解析参数并解析目标——因此，无法解析的操作名称或目标会产生与真实对话相同的 `Actions`类别控制台说明，而不只是到后续步骤失败时才显示。此路径不会像后端路径那样拒绝命令；步骤自身的前置条件（定义、执行器、目标要求）仍然是准入条件。

### 绕过调度器

如果要在不经过调度器的目标解析和执行流程的情况下，直接响应原始操作命令，请直接订阅 `ConvaiCharacter.OnActionsReceived` ：

```csharp
using System.Collections.Generic;
using Convai.Runtime.Components;
using Convai.Shared.Types;
using UnityEngine;

public sealed class ManualActionHandler : MonoBehaviour
{
    [SerializeField] private ConvaiCharacter _character;

    private void OnEnable() =>
        _character.OnActionsReceived += HandleActions;

    private void OnDisable() =>
        _character.OnActionsReceived -= HandleActions;

    private void HandleActions(IReadOnlyList<ConvaiActionCommand> commands)
    {
        foreach (ConvaiActionCommand cmd in commands)
            Debug.Log($"Action: {cmd.Name}, Target: {cmd.Target}");
    }
}
```

{% hint style="warning" %}
绕过分发器意味着不会自动解析目标，也不会应用批处理/失败策略或触发生命周期事件。这适用于只读观察或自定义分发管线，但不适用于通常应由 SDK 驱动行为的游戏玩法。
{% endhint %}

### 分发器的生命周期行为

| 情况                                                                        | 分发器行为                                                                   |
| ------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| 分发器已禁用                                                                    | 取消正在执行的任务；清空队列                                                          |
| 分发器已销毁                                                                    | 与禁用时相同                                                                  |
| 收到空批次                                                                     | 静默忽略，不触发任何事件                                                            |
| 操作名称未在本地定义中                                                               | 步骤失败： `OnStepFailed` 触发； `StopBatch` 中止批次                               |
| 未分配执行器字段                                                                  | 步骤失败： `OnStepFailed` 触发                                                 |
| 未满足目标要求                                                                   | 步骤失败： `OnStepFailed` 触发                                                 |
| 执行器返回 `Unhandled`                                                         | `OnStepUnhandled` 触发；对于 `StopBatch` 策略，将其视为失败                           |
| 匹配的操作定义中 `Enabled = false`                                                | 步骤被拒绝： `OnStepUnhandled` 触发，并显示一条指出该操作已禁用的消息；不会运行执行器                    |
| 批次的第一步设置了 `WaitForBotSpeech` （在命令或定义上）                                    | `OnStepStarted` 会延迟触发，直到角色语音开始、停止、轮次完成，或 `_speechGateTimeoutSeconds` 超时 |
| 玩家开始说话，且 `_cancelOnUserSpeech` 已启用                                        | 取消正在执行的步骤并清空队列； `OnCancelledByUserSpeech` 触发                            |
| 某个操作步骤超过其超时时间（其自身的 `TimeoutSeconds`，或 `_defaultStepTimeoutSeconds` （未设置时） | 步骤结果为 `TimedOut`; `OnStepFailed` 触发                                     |

### 使用示例

#### 示例 1 — 培训清单集成

**场景：** 企业入职培训模拟。NPC 完成每项设备演示后，清单 UI 随即推进。

在 Inspector 中将 `OnBatchCompleted` 连接到 `TrainingChecklistManager.AdvanceStep()`。每当 NPC 完成整个序列，清单就会自动推进。

```csharp
// TrainingChecklistManager.cs
public void AdvanceStep()
{
    _currentStep++;
    UpdateChecklistUI();
}
```

分发器端无需编写额外代码——只需在 Inspector 中连接 `OnBatchCompleted` UnityEvent。

#### 示例 2 — 导航失败时的备用对话

**场景：** 当 NPC 无法到达目标（NavMesh 路径受阻）时，它应说出一条备用语句，而不是默默停止。

订阅 `OnStepFailed` 并注入动态上下文更新：

```csharp
private void HandleStepFailed(ConvaiActionInvocation invocation)
{
    if (invocation.Command.Name == "Walk To")
    {
        string targetName = invocation.Command.Target ?? "that location";
        // 注入动态上下文，让 NPC 自然地回应此次失败
        _character.DynamicContext.AddEvent($"Unable to reach {targetName} — path was blocked.");
    }
}
```

### 后续步骤

{% content-ref url="/pages/c5598abd0ddd72fa75a0989ad602a5b4d12e16d7" %}
[编写自定义动作执行器](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/character-actions/writing-custom-executors.md)
{% endcontent-ref %}

{% content-ref url="/pages/0341126fa4c492311dab4fb6aca6d0c64191016b" %}
[角色动作脚本参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/character-actions/actions-scripting-reference.md)
{% endcontent-ref %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/character-actions/dispatcher-and-batch-policies.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
