> 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/core-concepts/event-system.md).

# 事件系统

Convai 组件和子系统上核心运行时 Blueprint 委托的参考，按类别组织并附带时序细节。

Convai Unreal Engine 插件通过 `UPROPERTY(BlueprintAssignable)` 组件和子系统上的委托，将核心运行时结果传递给 Blueprint。在角色或玩家 Blueprint 中绑定这些委托，即可驱动动画、更新 UI、分派操作，或响应连接状态变化。本页重点介绍核心运行时组件和子系统委托；异步代理、测试和视觉基础委托不在本核心概念参考的范围内。

### 继承的委托（两个组件均适用）

`UConvaiChatbotComponent` 和 `UConvaiPlayerComponent` 都继承自 `UConvaiConversationComponent`，而后者又继承自 `UConvaiAudioStreamer`。以下委托可用于每个对话组件。

#### 音频播放

这三个委托定义在 `UConvaiAudioStreamer` 中，聊天机器人和玩家组件均可使用。它们都不携带参数。在聊天机器人组件上，Talking 委托标记角色音频播放的起止边界。在玩家组件上，相同的委托由玩家语音回调广播，表示用户语音开始或停止。

| 委托                          | 类别                | 触发时机                         |
| --------------------------- | ----------------- | ---------------------------- |
| `OnStartedTalkingDelegate`  | `Convai`          | 聊天机器人：角色音频播放开始。玩家：用户语音开始。    |
| `OnFinishedTalkingDelegate` | `Convai`          | 聊天机器人：角色音频播放结束。玩家：用户语音停止。    |
| `OnFacialDataReadyDelegate` | `Convai\|LipSync` | 收到一批新的预计算面部动画数据，可供唇形同步流水线使用。 |

`OnStartedTalkingDelegate` 和 `OnFinishedTalkingDelegate` 是底层的语音起止边界事件。若要了解聊天机器人播放状态，请将 `UConvaiChatbotComponent::GetIsTalking` 与这些委托配合使用。若需专门处理播放中断，请绑定到 `OnInterruptedEvent`.

#### 转录

**`OnTranscriptionReceivedDelegate`** — 类别 `Convai|Transcription`

每当在一次话语期间或之后收到转录更新时都会触发。每轮对话会多次触发该委托：每次收到中间部分结果时触发一次，最终转录准备就绪时再触发一次。

| 参数                     | 类型                              | 说明                             |
| ---------------------- | ------------------------------- | ------------------------------ |
| `Speaker`              | `UConvaiConversationComponent*` | 其音频生成了此转录的组件。                  |
| `Listener`             | `UConvaiConversationComponent*` | 存在于委托签名中。当前的广播位置会传递 `nullptr`. |
| `Transcription`        | `FString`                       | 当前话语阶段的转录文本。                   |
| `IsTranscriptionReady` | `bool`                          | `true` 表示文本已准备好显示。             |
| `IsFinal`              | `bool`                          | `true` 当这是该话语的最后一次更新时。         |

#### 参与者连接状态

**`OnAttendeeConnectionStateChangedEvent`** — 类别 `Convai|Connection`

当聊天机器人或玩家组件上的参与者连接状态发生变化时触发。

| 参数                            | 类型                              | 说明                                                                                                                         |
| ----------------------------- | ------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `ConvaiConversationComponent` | `UConvaiConversationComponent*` | 拥有此事件的组件。                                                                                                                  |
| `AttendeeID`                  | `FString`                       | 状态发生变化的参与者标识符。                                                                                                             |
| `ConnectionState`             | `EC_ConnectionState`            | 新状态。此枚举定义了 `Disconnected`, `Connecting`, `Connected`和 `Reconnecting`；当前运行时路径会驱动 `Disconnected`, `Connecting`和 `Connected`. |

### 聊天机器人组件委托

这些委托位于 `UConvaiChatbotComponent` 仅在处理 AI 角色时才相关。

#### 收到的动作

**`OnActionReceivedEvent_V2`** — 显示名称 **收到动作时** — 类别 `Convai` （当前版本）

当 Convai 响应玩家输入或叙事触发器，发送一个或多个角色动作组成的序列时触发。可通过 `SequenceOfActions` 参数和聊天机器人的 `ActionsQueue`访问这些动作，因此你可以直接遍历事件参数，也可以使用 `FetchFirstAction` 和 `HandleActionCompletion` 来驱动基于队列的执行模型。

| 参数                           | 类型                            | 说明             |
| ---------------------------- | ----------------------------- | -------------- |
| `ChatbotComponent`           | `UConvaiChatbotComponent*`    | 收到这些动作的聊天机器人。  |
| `InteractingPlayerComponent` | `UConvaiPlayerComponent*`     | 其输入触发了这些动作的玩家。 |
| `SequenceOfActions`          | `TArray<FConvaiResultAction>` | 要执行的完整有序动作列表。  |

#### 情绪状态已更改

**`OnEmotionStateChangedEvent`** — 显示名称 **情绪状态更改时** — 类别 `Convai`

当 Convai 返回角色更新后的情绪状态时触发。触发此事件时， `EmotionState` 聊天机器人组件上的属性已更新。使用 `GetEmotionScore` 读取特定基本情绪的当前值，并将其应用到动画系统。

| 参数                           | 类型                         | 说明            |
| ---------------------------- | -------------------------- | ------------- |
| `ChatbotComponent`           | `UConvaiChatbotComponent*` | 情绪发生变化的聊天机器人。 |
| `InteractingPlayerComponent` | `UConvaiPlayerComponent*`  | 其输入触发情绪更新的玩家。 |

#### 角色数据已加载

**`OnCharacterDataLoadEvent_V2`** — 显示名称 **角色数据加载完成时** — 类别 `Convai` （当前版本）

插件尝试为聊天机器人组件加载角色数据后触发。此操作会在组件启动期间以及调用 `LoadCharacter` 后发生，包括通过 Blueprint setter 更改 `CharacterID` 的情况。使用 `Success` 参数判断是否应继续执行依赖角色的 UI 或设置逻辑。

| 参数                 | 类型                         | 说明                                          |
| ------------------ | -------------------------- | ------------------------------------------- |
| `ChatbotComponent` | `UConvaiChatbotComponent*` | 已加载数据的聊天机器人。                                |
| `Success`          | `bool`                     | `true` 表示获取成功； `false` 表示获取失败（例如，角色 ID 无效）。 |

#### 收到叙事章节

**`OnNarrativeSectionReceivedEvent`** — 显示名称 **收到叙事章节时** — 类别 `Convai`

当 AI 转入 Convai 控制面板中定义的 Narrative Design 图表新章节时触发。可据此同步游戏内状态——例如解锁门、推进任务标记或触发过场动画逻辑——以响应角色进入的叙事分支。

| 参数                   | 类型                         | 说明               |
| -------------------- | -------------------------- | ---------------- |
| `ChatbotComponent`   | `UConvaiChatbotComponent*` | 转入新章节的聊天机器人。     |
| `NarrativeSectionID` | `FString`                  | 控制面板中定义的叙事章节 ID。 |

#### 收到交互 ID

**`OnInteractionIDReceivedEvent`** — 显示名称 **收到交互 ID 时** — 类别 `Convai`

在玩家与角色之间每次独立交互（回合）开始时触发。交互 ID 可唯一标识此次交互，可用于日志记录、分析，或将动作序列与产生它们的回合关联起来。

| 参数                           | 类型                         | 说明          |
| ---------------------------- | -------------------------- | ----------- |
| `ChatbotComponent`           | `UConvaiChatbotComponent*` | 参与交互的聊天机器人。 |
| `InteractingPlayerComponent` | `UConvaiPlayerComponent*`  | 参与交互的玩家。    |
| `InteractionID`              | `FString`                  | 此交互的唯一标识符。  |

#### 已中断

**`OnInterruptedEvent`** — 显示名称 **中断时** — 类别 `Convai`

在应用 `InterruptSpeech` 后触发，并开始音频淡出。使用此事件将角色动画切换到“聆听”或“待机”姿势、重置字幕 UI，或清除任何“正在说话”状态指示。

| 参数                           | 类型                         | 说明                                              |
| ---------------------------- | -------------------------- | ----------------------------------------------- |
| `ChatbotComponent`           | `UConvaiChatbotComponent*` | 被中断的聊天机器人。                                      |
| `InteractingPlayerComponent` | `UConvaiPlayerComponent*`  | 存在于委托签名中。目前的 `InterruptSpeech` 实现会传递 `nullptr`. |

#### 失败

**`OnFailureEvent`** — 显示名称 **发生失败时** — 类别 `Convai`

声明为一个 `BlueprintAssignable` 不带参数的聊天机器人委托。 `UConvaiChatbotComponent::OnFailure()` 在调用相应处理程序时广播此事件。不要将其用作角色加载失败的主要信号；角色数据加载应使用 `OnCharacterDataLoadEvent_V2` 及其 `Success` 参数。

### 玩家组件委托

这些委托位于 `UConvaiPlayerComponent` 上，用于处理注视注意力状态的转换。玩家组件上的麦克风 API 基于函数（例如`GetIsStreaming`, `GetIsRecording`, `UnmuteStreamingAudio`等），而非基于事件——没有专用于麦克风的 `BlueprintAssignable` 委托。

#### 注视与注意力

所有四个注视委托都使用相同的签名：参与状态转换的玩家组件和对象组件。

| 委托                  | 显示名称 | 类别                               | 触发时机                                                                           |
| ------------------- | ---- | -------------------------------- | ------------------------------------------------------------------------------ |
| `OnGazeBegin`       | —    | `Convai\|Gaze Attention\|Events` | 玩家的注视光标首次进入某个 `UConvaiObjectComponent` 的边界范围时触发。此事件在任何注意力阈值之前触发。               |
| `OnGazeEnd`         | —    | `Convai\|Gaze Attention\|Events` | 玩家的注视离开 `UConvaiObjectComponent`，无论该对象是否已晋升为“受关注”状态。                           |
| `OnAttentionGained` | —    | `Convai\|Gaze Attention\|Events` | 对象被持续注视的时间超过 `GazeAttentionDelay` 秒后，系统会向符合条件的已注册聊天机器人发送注意力通知。                 |
| `OnAttentionLost`   | —    | `Convai\|Gaze Attention\|Events` | 发送注意力释放通知——原因可能是玩家移开视线的时间超过 `GazeAttentionLossDelay` 秒、另一个对象占据了该位置，或注意力目标已被销毁。 |

**注视委托签名：**

| 参数                | 类型                        | 说明         |
| ----------------- | ------------------------- | ---------- |
| `PlayerComponent` | `UConvaiPlayerComponent*` | 注视发生变化的玩家。 |
| `ObjectComponent` | `UConvaiObjectComponent*` | 参与状态转换的对象。 |

新的注视开始事件和注意力获得事件要求玩家组件上的 `bEnableGazeAttention` 设置为 `true` 。如果对象处于受关注状态时禁用了注视注意力，则可以释放当前注意力，并仍会广播注意力丢失事件。

晋升和释放阈值可在 `UConvaiPlayerComponent`: `OnAttentionGained` 对象持续处于注视状态 `GazeAttentionDelay` 秒后（默认值为 `1.0` 秒）。 `OnAttentionLost` 注视中断 `GazeAttentionLossDelay` 秒后（默认值为 `5.0` 秒后触发（默认值为 **详情** 面板中调整这两个值，以匹配体验所需的交互速度。

### 对象组件事件

`UConvaiObjectComponent` 提供四个注视事件，从对象的角度对应玩家组件的注视委托。使用这些事件，即可直接在对象的蓝图中响应玩家的注视，无需轮询玩家组件。

| 委托                  | 类别                     | 触发时机                                                               |
| ------------------- | ---------------------- | ------------------------------------------------------------------ |
| `OnGazedIn`         | `Convai\|Object\|Gaze` | 玩家的注视光标进入此对象时触发。任何注意力阈值达成之前都会触发。                                   |
| `OnGazedOut`        | `Convai\|Object\|Gaze` | 玩家的注视离开此对象时触发，无论注意力状态如何。                                           |
| `OnAttentionGained` | `Convai\|Object\|Gaze` | 持续注视达到阈值后，此对象会向符合条件的已注册聊天机器人发送注意力获得通知。                             |
| `OnAttentionLost`   | `Convai\|Object\|Gaze` | 计时器到期或注视转移到另一个对象时，此对象会发送注意力丢失通知。目标被销毁时的处理由玩家级别的注意力丢失委托负责，其对象参数可为空。 |

**对象注视事件签名：**

| 参数                | 类型                        | 说明                                               |
| ----------------- | ------------------------- | ------------------------------------------------ |
| `ObjectComponent` | `UConvaiObjectComponent*` | 注视状态发生变化的对象。                                     |
| `PlayerComponent` | `UConvaiPlayerComponent*` | 触发此次状态转换的注视所属玩家。可能为 `null` （目标被销毁时）；使用前务必检查是否为空。 |

这些事件仅在 `bGazeable` 在对象组件上设为 `true` 时触发（默认值）。对于应存在于聊天机器人的环境中、用于动作或上下文目的，但不应被玩家注视到的对象，请将 `bGazeable` 设为 `false` 。

### 子系统事件

`UConvaiSubsystem` 提供两个 `BlueprintAssignable` 委托，用于监控游戏实例中所有会话的全局连接状态。可通过任意蓝图访问子系统： **Get Game Instance → Get Subsystem (Convai Subsystem)**.

| 委托                                    | 类别                   | 参数                                   | 触发时机                                                                                    |
| ------------------------------------- | -------------------- | ------------------------------------ | --------------------------------------------------------------------------------------- |
| `OnServerConnectionStateChangedEvent` | `Convai\|Connection` | `EC_ConnectionState ConnectionState` | 全局 WebRTC 连接状态发生变化。使用 `ConnectionState` 参数，对 `Connecting` 或 `Connected`.                |
| `OnUserIdleWarning`                   | `Convai\|Event`      | `int32 RemainingSeconds`             | Convai 检测到用户处于空闲状态。 `RemainingSeconds` 表示连接自动关闭前剩余的时间。调用子系统上的 `ResetIdleTimer` 以防止断开连接。 |

绑定到 `OnServerConnectionStateChangedEvent` ，以便 UI 覆盖层或日志能够响应任意会话状态变化。绑定到 `OnUserIdleWarning` ，以提示用户或以编程方式重置计时器。例如，在培训模拟中，无论学员是否发言，都可在其完成一个任务步骤时重置计时器。

### 事件绑定模式

#### 蓝图

使用 **Assign** 节点，在组件引用上绑定任何 `BlueprintAssignable` 委托。对于聊天机器人事件，请在所属角色蓝图的 `BeginPlay`中绑定。如果处理程序依赖于角色数据已加载（例如显示角色名称），则应改为在 `OnCharacterDataLoadEvent_V2` 处理程序中绑定。对于子系统事件，请在从游戏实例获取子系统后进行绑定。

{% hint style="warning" %}
每个委托只绑定一次——通常在 `BeginPlay`中。避免在委托回调中绑定，或在演员生命周期内可能被调用多次的函数中绑定。每次调用 **绑定** 会添加新的绑定；重复绑定会导致同一处理程序针对每个事件触发多次。
{% endhint %}

#### C++

在 C++ 中，使用 `AddDynamic` 在 `BeginPlay` 中，并使用 `RemoveDynamic` 在 `EndPlay` 以匹配蓝图绑定模式。

```cpp
// AMyCharacter.h
UFUNCTION()
void HandleEmotionChanged(UConvaiChatbotComponent* ChatbotComp,
                          UConvaiPlayerComponent* PlayerComp);

UFUNCTION()
void HandleConnectionStateChanged(EC_ConnectionState NewState);
```

```cpp
// AMyCharacter.cpp
void AMyCharacter::BeginPlay()
{
    Super::BeginPlay();

    // 绑定聊天机器人委托
    if (ChatbotComponent)
    {
        ChatbotComponent->OnEmotionStateChangedEvent.AddDynamic(
            this, &AMyCharacter::HandleEmotionChanged);
    }

    // 绑定子系统委托
    if (UConvaiSubsystem* Subsystem = GetGameInstance()->GetSubsystem<UConvaiSubsystem>())
    {
        Subsystem->OnServerConnectionStateChangedEvent.AddDynamic(
            this, &AMyCharacter::HandleConnectionStateChanged);
    }
}

void AMyCharacter::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
    if (ChatbotComponent)
    {
        ChatbotComponent->OnEmotionStateChangedEvent.RemoveDynamic(
            this, &AMyCharacter::HandleEmotionChanged);
    }

    if (UConvaiSubsystem* Subsystem = GetGameInstance()->GetSubsystem<UConvaiSubsystem>())
    {
        Subsystem->OnServerConnectionStateChangedEvent.RemoveDynamic(
            this, &AMyCharacter::HandleConnectionStateChanged);
    }

    Super::EndPlay(EndPlayReason);
}
```

在 `EndPlay` 中移除动态委托，以便解除绑定由 Actor 拥有的处理程序，尤其是对于所有者生命周期长于单个 Actor 的子系统事件。

### 用法示例

#### 由情绪驱动的动画

每当 Convai 返回新的情绪状态时，都会更新面部表情的角色。

在蓝图中， **绑定** 到 **On Emotion State Changed** 角色的 `BeginPlay` 事件。处理程序节点会接收聊天机器人组件引用——调用其 **Get Emotion Score** 以读取当前情绪值，并将其传递给动画系统或动画蓝图。

在 C++ 中，使用 `AddDynamic` 在 `BeginPlay`:

```cpp
// BeginPlay
ChatbotComponent->OnEmotionStateChangedEvent.AddDynamic(
    this, &AMyCharacter::HandleEmotionChanged);

// 触发时 EmotionState 已更新
void AMyCharacter::HandleEmotionChanged(UConvaiChatbotComponent* ChatbotComp,
                                         UConvaiPlayerComponent* PlayerComp)
{
    // 使用 GetEmotionScore() 驱动动画蓝图
}
```

预期结果：角色的面部表情会在携带情绪数据的同一段音频响应中更新。

#### 连接状态 UI 覆盖层

当 Convai 会话尚未就绪时，显示“正在连接…”覆盖层的 HUD。

在蓝图中，从游戏实例获取 **Convai 子系统** ，在 HUD 的 `BeginPlay`中，然后将 **Assign** 绑定到 **On Server Connection State Changed**。在处理程序中，根据收到的状态是否为 `Connected`.

来显示或隐藏覆盖层控件。预期结果：覆盖层在 `Connecting` 期间可见，并在会话达到 `Connected` 时自动隐藏——无需在 `Tick`.

#### 动作调度系统

一个按顺序执行一系列物理动作（移动、交互、说话）的角色。

在蓝图中， **将** 绑定到 **On Actions Received** ，并在 `BeginPlay`中完成。在处理程序中，调用 **Fetch First Action** 从队列中读取第一个动作，执行相应的游戏逻辑（移动角色、触发动画、打开道具），然后调用 **Handle Action Completion** 并传入 `true`。成功完成后，当前动作会从队列中移除，下一个动作即可读取。

预期结果：每个动作在前一个动作报告完成后按顺序执行，同时角色的语音并行播放。

### 故障排查

| 症状             | 可能原因                                                                           | 解决方法                                                                                                                                  | 验证                                                               |
| -------------- | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- |
| 委托从未触发         | 从未建立绑定，或绑定是在事件已经触发后才创建的                                                        | 在角色蓝图的 `BeginPlay` 中使用 **Assign** 节点进行绑定，或在 C++ 中使用 `AddDynamic` 。对于依赖角色数据的事件，请在 `OnCharacterDataLoadEvent_V2` 处理程序，而不是在 `BeginPlay`. | 添加一个 **打印字符串** 到处理程序中；预期条件出现时，它应输出内容。                            |
| 处理程序针对每个事件触发多次 | 委托被绑定了多次——例如， **Assign** 位于一个每次调用时都会执行的函数中 `StartSession`                      | 确保每个 **Assign** 调用在每个 Actor 生命周期内恰好执行一次。如果有意重新绑定，请先调用 **Remove** （蓝图）或 `RemoveDynamic` （C++），然后再重新分配。                                 | 在处理程序中记录计数器；每个事件触发时，计数器应恰好递增 1。                                  |
| 会话开始时角色数据设置失败  | 无效的 `CharacterID` 或 API 密钥配置问题                                                 | 请确认 `CharacterID` 聊天机器人组件中的设置与 Convai 控制面板中的某个角色匹配。请在 **Convai 编辑器窗口**.                                                               | `OnCharacterDataLoadEvent_V2` 触发时， `Success = true` 应在有效会话开始后出现。 |
| 从未触发注视事件       | `bEnableGazeAttention` 在玩家组件上为 `false` ，或者目标 Actor 没有 `UConvaiObjectComponent` | 将 **启用注视注意力** 设置为 `true` （在玩家组件上）。确认目标 Actor 上有一个 `UConvaiObjectComponent` ，并且已启用 `bGazeable` 。                                       | `OnGazeBegin` 当玩家看向目标时，会在玩家组件和对象组件上触发。                           |

### 相关概念

使用这些页面了解委托触发时机与回合行为、组件所有权及会话生命周期决策之间的关系。

{% content-ref url="/pages/422d78b3fb4f61a00785b876137cbfde618d7baa" %}
[对话流程](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unreal-engine-plugin/core-concepts/conversation-flow.md)
{% endcontent-ref %}

{% content-ref url="/pages/0a71bb8fce84999367c663a06434475b944f88da" %}
[运行时架构](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unreal-engine-plugin/core-concepts/runtime-architecture.md)
{% endcontent-ref %}

{% content-ref url="/pages/a8878427b216a80d6b385f1a342c440aa9b398c9" %}
[会话生命周期](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unreal-engine-plugin/core-concepts/session-lifecycle.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/core-concepts/event-system.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.
