> 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/usage-examples.md).

# 角色动作示例

Convai 角色动作系统的渐进式示例——Inspector 设置、事件订阅、脚本批量注入和观察动作。

这六个示例从最简单的配置逐步介绍到完全通过脚本控制。每个示例都可独立使用——你无需先阅读其他示例，也可以直接参照其中任意一个。

### 示例 1 — 消防安全检索（Inspector 设置，无需编写代码）

**场景：** 消防安全培训模拟。学员提出请求时，讲师 NPC 会取来灭火器。无需编写脚本。

**前提条件：** 场景中已烘焙 NavMesh。

#### Inspector 配置

在讲师 NPC 的 `GameObject`上添加以下组件：

* `ConvaiCharacter`
* `ConvaiActionConfigSource`
* `ConvaiActionDispatcher` （两项策略均保留默认值：Queue、StopBatch）
* `ConvaiWalkToActionExecutor` — `_arriveDistance = 0.6`
* `ConvaiPointAtActionExecutor` —将 `Hold Seconds` 保留 `3`。它通过 `ConvaiBodyAnimationController`来驱动手臂动作，因此角色也需要添加该组件。

在 `ConvaiActionConfigSource`:

**中定义操作：**

| 操作名称       | 目标要求     | 执行器                           |
| ---------- | -------- | ----------------------------- |
| `Retrieve` | `物体`     | `ConvaiWalkToActionExecutor`  |
| `Point At` | `Either` | `ConvaiPointAtActionExecutor` |

**可操作对象：**

| 名称             | 说明                              |
| -------------- | ------------------------------- |
| `Extinguisher` | 主泵控制面板旁的墙上支架上安装着一具红色便携式 CO2 灭火器 |
| `Alarm Panel`  | 场地入口附近安装着紧急警报面板，带有红色拉柄          |

**预期结果：**

* “拿灭火器” → NPC 会走到灭火器旁，并在距离其 0.6 个单位处停下。
* “指向警报面板” → NPC 会朝警报面板抬起手臂，保持指向 3 秒，然后放下手臂。
* “拿警报器” → Convai 会根据描述，正确地将“警报器”解析为“Alarm Panel”。

{% hint style="success" %}
打开 Console 并按以下内容筛选： `ConvaiActionDebugProbe` （如果已添加该探针）。你应该会看到：

```
[ConvaiActionDebugProbe] Step succeeded #1: cmd='Retrieve Extinguisher', def='Retrieve', target=Object:Extinguisher
```

{% endhint %}

### 示例 2 — 入职清单集成（事件订阅）

**场景：** 企业入职培训模拟。NPC 演示每个工作站时，清单 UI 会随之更新。完成全部设备巡览后，培训阶段随之推进。

#### C# 设置

连接 `OnBatchCompleted` 发送给清单管理器。如果在 Inspector 中完成接线，分发器端无需编写额外代码。若要通过代码接线：

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

public sealed class OnboardingTourController : MonoBehaviour
{
    [SerializeField] private ConvaiActionDispatcher _dispatcher;
    [SerializeField] private TrainingChecklistUI _checklist;

    private void OnEnable()
    {
        _dispatcher.OnBatchCompleted.AddListener(HandleTourStepCompleted);
        _dispatcher.OnBatchAborted.AddListener(HandleTourStepFailed);
    }

    private void OnDisable()
    {
        _dispatcher.OnBatchCompleted.RemoveListener(HandleTourStepCompleted);
        _dispatcher.OnBatchAborted.RemoveListener(HandleTourStepFailed);
    }

    private void HandleTourStepCompleted()
    {
        _checklist.MarkCurrentStepComplete();
        _checklist.AdvanceToNextStep();
    }

    private void HandleTourStepFailed()
    {
        _checklist.MarkCurrentStepIncomplete();
    }
}
```

**ConvaiActionConfigSource 定义：**

| 操作名称          | 目标要求 | 执行器                          |
| ------------- | ---- | ---------------------------- |
| `Walk To`     | `物体` | `ConvaiWalkToActionExecutor` |
| `Demonstrate` | `物体` | `ConvaiLookAtActionExecutor` |

**可交互对象：** 每个工作站均已注册，并附有名称和位置描述。

**预期结果：** 受训者说“带我看看文件归档系统”。NPC 走到文件柜前，面向文件柜，并触发 `OnBatchCompleted` ——清单会自动进入下一步。

### 示例 3 — 导航失败时使用备用对话（错误恢复）

**场景：** 建筑工地安全模拟。当 NPC 无法抵达危险区域（路径被阻挡）时，它会说明遇到的障碍，而不是悄无声息地停止。

#### C# 设置

订阅 `OnStepFailed` 并注入动态上下文事件，让 NPC 自然地说出备用回应：

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

public sealed class ActionFailureHandler : MonoBehaviour
{
    [SerializeField] private ConvaiActionDispatcher _dispatcher;
    [SerializeField] private ConvaiCharacter _character;

    private void OnEnable() =>
        _dispatcher.OnStepFailed.AddListener(HandleStepFailed);

    private void OnDisable() =>
        _dispatcher.OnStepFailed.RemoveListener(HandleStepFailed);

    private void HandleStepFailed(ConvaiActionInvocation invocation)
    {
        if (invocation.Command.Name != "Move To") return;

        string targetName = string.IsNullOrEmpty(invocation.Command.Target)
            ? "that location"
            : invocation.Command.Target;

        // 告知 Convai 发生了什么，以便 NPC 自然地对此作出回应
        _character.DynamicContext.AddEvent(
            $"Movement to '{targetName}' failed — the path was blocked.");
    }
}
```

**预期结果：** NPC 朝危险区域移动， `NavMeshAgent` 未能完成路径导航，执行器返回 `Failed`，并 `OnStepFailed` 触发。此时会注入备用事件，NPC 会说类似这样的话：“我无法前往化学品储存区——脚手架挡住了通道。”

将 `FailurePolicy` 设为 `StopBatch` （默认值），这样同一批次中的后续步骤（例如“演示危险情况”）就不会在导航步骤失败后继续执行。

### 示例 4 — 脚本化演示序列（以编程方式注入）

**场景：** 医疗操作培训模拟。在培训脚本的指定时刻（由时间线事件触发），NPC 会自动演示设备操作，无需等待学员提出要求。

#### C# 设置

使用 `ConvaiActionDispatcher.EnqueueActions` 通过时间线触发器或 UI 按钮注入多步骤序列：

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

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

    // Call this from a Unity Timeline signal, UI button, or game event
    public void RunDefibrillatorDemo()
    {
        _dispatcher.EnqueueActions(new List<ConvaiActionCommand>
        {
            new ConvaiActionCommand("Move To", "Equipment Cart"),
            new ConvaiActionCommand("Pick Up", "Defibrillator"),
            new ConvaiActionCommand("Move To", "Patient Bed"),
            new ConvaiActionCommand("Point At", "Patient Bed")
        });
    }
}
```

将 `RunDefibrillatorDemo` 关联到 `UnityEngine.Timeline` 信号、UI 按钮 `OnClick`或场景中的任何其他触发器。

**预期结果：** 教师 NPC 会前往设备推车，拿起除颤器，走到病床旁并指向病床——整个过程无需学员说任何话。 `OnBatchCompleted` 会在序列完成时触发，可用于推进培训阶段。

{% hint style="info" %}
`BatchPolicy = Queue` 可确保学员正在与一个活动动作批次进行对话时，此脚本化序列会耐心等待。若演示应中断任何正在进行的动作，则改用 `BatchPolicy = ReplaceCurrent` 。
{% endhint %}

### 示例 5 — 与语音同步的展品讲解（语音门控）

**场景：** 博物馆导览模拟。访客询问展品时，NPC 会口头回答，然后指向展品。必须等角色语音真正开始播放后才能开始指向动作，否则 NPC 看起来会像是在开口说话之前就指向展品。

#### C# 设置

在命令上设置 `WaitForBotSpeech` 和 `DelayAfterBotSpeechSeconds` ，然后再将其加入队列：

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

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

    // Call this once the NPC's spoken answer has been dispatched for this turn
    public void PointAtExhibit(string exhibitName)
    {
        var pointAction = new ConvaiActionCommand("Point At", exhibitName)
        {
            WaitForBotSpeech = true,
            DelayAfterBotSpeechSeconds = 0.3f
        };

        _dispatcher.EnqueueActions(new List<ConvaiActionCommand> { pointAction });
    }
}
```

**预期结果：** `pointAction` 是新批次的第一步，因此 `ConvaiActionDispatcher` 会在语音门控处将其暂存，暂不执行。角色的 `OnSpeechStarted`, `OnSpeechStopped`或 `OnTurnCompleted` 事件中任意一个先触发，门控就会释放；之后还会等待在 `DelayAfterBotSpeechSeconds` 中设置的额外 0.3 秒，然后才执行指向手势。

只有批次的第一步会受到这种门控。如果这些事件都没有触发，调度器的 `_speechGateTimeoutSeconds` 字段仍会释放该步骤（默认值为 2 秒，在 Inspector 的 Dispatch 标题下显示为“语音门控超时秒数”），因此即使这一轮没有语音，也不会让批次停滞。

### 示例 6 — 博物馆展品的距离检查（观察类动作）

**场景：** 一个博物馆导览模拟场景。访客询问某件展品有多远，NPC 给出距离，而不是执行动作。这种动作与前五个示例的形式不同：执行器的任务是组织答案，而不是移动或做手势。

#### Inspector 配置

在讲解员 NPC 的 `GameObject`上，添加 `ConvaiMeasureDistanceActionExecutor` (`添加组件 > Convai > Actions > Measure Distance`）。它不需要配套组件；如果没有解析到目标，它就会测量到玩家的距离。

在 `ConvaiActionConfigSource`:

**中定义操作：**

| 操作名称               | 目标要求     | 执行器                                   |
| ------------------ | -------- | ------------------------------------- |
| `Measure Distance` | `Either` | `ConvaiMeasureDistanceActionExecutor` |

将执行器的 **Distance Bands** 字段保留默认值（`Within Reach` `1.2`, `A Few Steps` `3.5`, `Across The Area` `9`），并勾选 **Include Metres** ，使口头回答包含测量值。

在动作定义中，将 **Answer Delivery** 设为 `Tell The Player` ——这是 SDK 对任何用于回答问题的动作（例如读取仪表、计数或测量距离）的建议设置。

**预期结果：**

* “恐龙骨架有多远？”→ 执行器解析目标，测量地面平面上的距离，并返回已回答结果，例如 `The Dinosaur Skeleton is a few steps away. About 2.8 metres.` ——Convai 会将答案说给访客听。
* “我离你有多远？”→ 如果没有解析到目标，执行器就会改为测量到玩家的距离，并回答 `You are within reach. About 0.9 metres.`

`ConvaiMeasureDistanceActionExecutor` 返回 `ConvaiActionExecutionResult.Answered(...)` 而不是 `Succeeded(...)`。已回答的结果包含 Convai 获准说出的句子；结果中的其他内容都不会传递给角色的世界模型。 `ConvaiCountTargetGroupActionExecutor` (`Convai/Actions/Count Target Group`）遵循相同模式，用于统计某个 `ConvaiActionTargetGroup`.

### 后续步骤

{% content-ref url="/pages/1398e3302b345ef93934a0e6c93b4d8e576ab00e" %}
[排查角色动作问题](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/character-actions/debugging-and-troubleshooting.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/usage-examples.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.
