> 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-unreal-engine-plugin/features/character-actions/character-actions-examples.md).

# 角色动作示例

端到端动作方案：导航到已注册对象、跟随角色，以及在 Convai Unreal Engine 插件中使用参数化动作。

下面的每个示例都是自包含的：列出了实现可用操作所需的 Details 面板配置和 Blueprint 处理程序伪代码。如果你刚开始接触角色操作，请从示例 1 开始。示例从默认导航逐步介绍到带类型化参数的自定义操作。

### 示例 1：导航到已注册的对象

**场景：** 在训练模拟中，学员要求 NPC 指导员前往某处时，NPC 指导员会导航到一件设备旁。

#### 配置

在 NPC Actor 的 **Details** 面板中，位于 **Convai Chatbot > Environment**:

1. **Enable Actions** 处的复选框已勾选。
2. `Actions` 数组包含一个 `Move To` 条目，其中有一个 `destination` 参数，类型为 **Actor Reference** （这是默认值）。
3. `Objects` 数组包含一个条目：
   * `Name`: `"SafetyValve"`
   * `Ref`：关卡中的阀门 Actor
   * `Object Is`: `Whole Actor`
   * `AcceptanceRadius`: `100.0`

#### Blueprint 处理程序 — Move To

向 NPC Actor Blueprint 添加一个名为 **Custom Event** 的 `Move To` 事件，并添加一个 `FConvaiResultAction` 输入：

```
// Blueprint 伪代码
Event Move To(ActionData: FConvaiResultAction)
    // 读取目标对象引用
    DestEntry = GetParamAsRef(ActionData, "destination")

    // 将条目解析为 AI Move To 所需的输入
    ResolveGoalLocation(
        Entry = DestEntry,
        SourceActor = Self,
        // 输出：
        TargetActor, ObjectActor, ObjectComponent, Destination,
        OutAcceptanceRadius, bUsesDestination,
        bSuccess, bAlreadyThere, bReachable, PathEnd, PathPoints,
        GoalTravelDistance, MovementPointIndex
    )

    if not bSuccess:
        AbortActionSequence(
            EventText = "Destination actor no longer exists",
            ShouldRespond = Always
        )
        return

    if bAlreadyThere:
        HandleActionCompletion(IsSuccessful = true)
        return

    // 将两个引脚直接连接到同一个 AI Move To，无需分支。
    // 仅当 Destination 应优先时，Target Actor 才为 null。
    AIMoveTo(Target = TargetActor, Destination = Destination, AcceptanceRadius = OutAcceptanceRadius)

    // 通过 OnMoveCompleted 等待 AIMoveTo 完成
    // 然后调用：
    HandleActionCompletion(IsSuccessful = true)
```

{% hint style="info" %}
在执行 `bOut Success` 和 `bOut Already There` 之后，再调用 `AI Move To`。如果解析失败， `Destination` 中保存的是过时的快照，而 `Target Actor` 为 `null` ——即便如此仍然发出移动指令，也会让 Pawn 前往过时的位置。 `AI Move To` Convai Move To
{% endhint %}

异步节点会封装相同的解析过程，并在内部发出移动指令——请参阅 `Convai Move To` ，了解这种更简便的替代方案，无需手动连接 [Actions Blueprint 参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unreal-engine-plugin/features/character-actions/actions-blueprint-reference.md) 。 `Resolve Goal Location` 和 `AI Move To` 。

***

### 示例 2：跟随角色

**场景：** 一个安保训练 NPC 沿巡逻路线跟随玩家，直到收到停止指令。

#### 配置

1. `Actions` 数组包含 `Follow` （名称： `"Follow"`，参数： `character`，类型： **Actor 引用**）和 `Stop Moving` （名称： `"Stop Moving"`，无参数）——两者都是默认项。
2. `Characters` 数组包含：
   * `名称`: `"Player"` 或与玩家的 `玩家名称` 字段匹配，该字段位于 `Convai Player` 组件上。
   * `引用`：玩家 Pawn Actor。

#### 蓝图处理程序 — 跟随

```
// Blueprint 伪代码
事件 Follow(ActionData: FConvaiResultAction)
    TargetEntry = GetParamAsRef(ActionData, "character")

    if TargetEntry.Ref is None:
        AbortActionSequence(
            EventText = "Cannot find the character to follow",
            ShouldRespond = Always
        )
        return

    // 启动重复计时器或使用跟踪任务
    // 在每个 tick 中持续向 TargetEntry.Ref 发出 AIMoveTo

    // 循环启动后完成 Follow 动作。
    // 计时器/任务会持续运行，直到稍后触发 Stop Moving。
    HandleActionCompletion(IsSuccessful = true)
```

#### 蓝图处理程序 — 停止移动

事件名称必须与已注册的动作名称完全一致，包括空格。由于默认动作注册为 `"Stop Moving"` （带空格），蓝图自定义事件也必须命名为 `Stop Moving` — 而不是 `StopMoving`.

```
// Blueprint 伪代码
Event Stop Moving(ActionData: FConvaiResultAction)
    // 取消重复移动计时器/任务
    StopFollowTask()

    // 停止 Pawn 移动
    StopMovement on AIController

    HandleActionCompletion(IsSuccessful = true)
```

{% hint style="warning" %}
`跟随` 会启动持续运行的行为，但动作本身应在跟随循环启动后完成。这样后续动作（包括 `停止移动`）便可正常调度。
{% endhint %}

***

### 示例 3：带字符串选项的参数化动作

**场景：** 在医疗模拟中，NPC 会根据指示，从固定列表中选择一种治疗方案并实施。

#### 配置

向 `动作` 数组添加自定义动作：

* `名称`: `"Administer Treatment"`
* `描述`: `"Administer a specific treatment to the patient"`
* 参数：
  * `名称`: `"treatment"`
  * `类型`: `字符串`
  * `选项`: `["CPR", "Defibrillation", "IV Fluids", "Oxygen Mask"]`

#### 蓝图处理程序

```
// Blueprint 伪代码
事件 Administer Treatment(ActionData: FConvaiResultAction)
    TreatmentName = GetParamAsString(ActionData, "treatment")

    // 根据治疗类型进行分支
    switch TreatmentName:
        case "CPR":            PlayCPRAnimation()
        case "Defibrillation": PlayDefibrillationAnimation()
        case "IV Fluids":      PlayIVFluidsAnimation()
        case "Oxygen Mask":    PlayOxygenMaskAnimation()
        default:
            AbortActionSequence(
                EventText = "Unknown treatment: " + TreatmentName,
                ShouldRespond = Always
            )
            return

    // 等待动画播放
    延迟 2.0 秒

    HandleActionCompletion(
        IsSuccessful = true,
        bAutoReport = true,
        AdditionalNote = TreatmentName + " administered"
    )
```

***

### 示例 4：使用枚举的参数化操作

**场景：** 企业入职场景中的 NPC 会根据指令改变姿势。

#### 配置

假设已有一个 `UENUM` ，名为 `ENPCPosture` 其值包括 `Standing`, `Sitting`, `Crouching`.

添加自定义操作：

* `Name`: `"Change Posture"`
* 参数：
  * `Name`: `"posture"`
  * `Type`: `Enum`
  * `EnumType`: `ENPCPosture`

#### 蓝图处理程序

```
// Blueprint 伪代码
事件 Change Posture(ActionData: FConvaiResultAction)
    PostureByte = GetParamAsByte(ActionData, "posture")
    Posture = ByteToEnum<ENPCPosture>(PostureByte)

    switch Posture:
        case Standing:  SetPostureAnimation(Standing)
        case Sitting:   SetPostureAnimation(Sitting)
        case Crouching: SetPostureAnimation(Crouching)

    HandleActionCompletion(IsSuccessful = true)
```

***

### 示例 5：使用动态字符串参数进行打印

**场景：** 训练 NPC 在收到请求时，会将 Convai 提供的文本打印到屏幕上。

#### 配置

向 `动作` 数组添加自定义动作：

* `Name`: `"Print"`
* 参数：
  * `Name`: `"text"`
  * `类型`: `字符串`
  * `描述`：留空或使用简短提示

编译 Blueprint，然后使用以下内容搭建处理程序： **创建 Convai Action Handler**.

#### 蓝图处理程序

```
// Blueprint 伪代码
事件 Print(ActionData: FConvaiResultAction)
    Message = GetParamAsString(ActionData, "text")
    Print String(Message)
    HandleActionCompletion(IsSuccessful = true, ShouldRespond = Never)
```

**测试提示：** `"在屏幕上打印你的名字。"`

***

### 示例 6：提供选项并设置回退方案的舞蹈

**场景：** 角色通过单个动作播放多个舞蹈蒙太奇中的一个。

#### 配置

1. 为每种舞蹈风格创建一个 `Anim Montage` 。调整每个蒙太奇的混合进入/退出设置。
2. 添加动作 `Dance` 并添加一个参数：
   * `Name`: `"type"`
   * `类型`: `字符串`
   * `Choices`: `["groove", "disco", "g-style"]`

#### 蓝图处理程序

```
// Blueprint 伪代码
事件 Dance(ActionData: FConvaiResultAction)
    DanceType = GetParamAsString(ActionData, "type")

    按字符串 (DanceType) 分支：
        case "groove":  PlayMontage(GrooveMontage, onComplete, onInterrupted)
        case "disco":   PlayMontage(DiscoMontage, onComplete, onInterrupted)
        case "g-style": PlayMontage(GStyleMontage, onComplete, onInterrupted)
        default:
            HandleActionCompletion(
                IsSuccessful = false,
                bAutoReport = true,
                ShouldRespond = Always,
                AdditionalNote = "That dance style is not available",
                Delay = 1.5
            )
            return

    // 将 onComplete 和 onInterrupted 连接到：
    HandleActionCompletion(IsSuccessful = true, ShouldRespond = Never)
```

**测试提示：** `"给我展示 groove 舞。"` （播放蒙太奇）， `"跳一段芭蕾舞。"` （回退分支——角色说明该舞蹈风格不可用）。

***

### 示例 7：语音开始后启动序列

**场景：** 安全演习 NPC 在开始口头警告后，先指向出口标志，然后走向该标志。

#### 配置

在 `Actions` 数组中添加两个动作：

1. `Announce` ——自定义动作，无参数， `bWaitForBotSpeech = true`, `DelayAfterBotSpeechSec = 0.5`.
2. `移动到` （默认）— `bWaitForBotSpeech = false`.

当 Convai 生成响应时 `"Announce, Move To ExitSign"` 当操作队列为空时，插件：

1. 接收 `Announce` 作为新序列中的第一个操作。
2. 由于 `Announce` 的 `bWaitForBotSpeech = true`会一直等待，直到角色开始说话、说话结束、触发无响应路径，或操作等待超时。
3. 在等待条件满足后再过 `Announce` 秒时触发 `0.5` 秒。
4. 在 `移动到` 之后 `Announce` 处理程序调用 `HandleActionCompletion(true)`.

#### 蓝图处理程序 — Announce

```
// Blueprint 伪代码
事件 Announce(ActionData: FConvaiResultAction)
    // 播放公告动画 / 音频提示
    PlayAnnouncementAnim()

    HandleActionCompletion(
        IsSuccessful = true,
        bAutoReport = true,
        ShouldRespond = Never
    )
```

***

### 后续步骤

{% content-ref url="/pages/e29ff52f0d30b08b7f190e5b10f7b84aa21c7ff4" %}
[参数化动作](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unreal-engine-plugin/features/character-actions/parameterized-actions.md)
{% endcontent-ref %}

{% content-ref url="/pages/8e18d509947b40274dca96b384f432486348198f" %}
[动作 Blueprint 参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unreal-engine-plugin/features/character-actions/actions-blueprint-reference.md)
{% endcontent-ref %}

{% content-ref url="/pages/8c96d39684a8203fb0c40d8bcb7467ca8267e3c9" %}
[排查角色动作问题](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unreal-engine-plugin/features/character-actions/troubleshoot-character-actions.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-unreal-engine-plugin/features/character-actions/character-actions-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.
