> 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/scripting-reference/session-events.md).

# 会话事件

会话级事件参考文档，涵盖连接状态、错误、空闲警告和参与者变更，可通过 Inspector 中继器或脚本接入。

SDK 通过两种接线方式提供会话级事件，你可以单独使用，也可以组合使用。 `ConvaiSessionEventRelay` 是一个 MonoBehaviour，可将事件连接到在 Inspector 中指定的 `UnityEvent` 回调，无需编写代码。 `ConvaiEvents` 是一个 C# 类型化事件中心，可通过以下方式从任何脚本访问： `ConvaiManager.ActiveManager.Events`。两种方式都会触发相同的底层 SDK 事件——请根据代码需求选择。有关中继组件的概念性概述以及如何选择不同方式，请参阅 [事件系统](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/core-concepts/event-system.md).

***

### Inspector 接线 — `ConvaiSessionEventRelay`

{% tabs %}
{% tab title="Inspector" %}
**设置：**

1. 通过以下方式将 `ConvaiSessionEventRelay` 添加到场景中的任意 GameObject： **Add Component → Convai → Events → Convai Session Event Relay**.
2. 在 `ConvaiManager` 字段中指定一个引用， **Manager** 也可以将其留空并启用 **Auto Resolve Manager** ，以便在运行时使用 `ConvaiManager.ActiveManager` 。
3. 在 Inspector 中为各个事件接入回调。

{% hint style="warning" %}
**Auto Resolve Manager** 使用起来很方便，但结果不确定。对于包含多个 `ConvaiManager` 实例的场景，请明确指定目标管理器。
{% endhint %}
{% endtab %}

{% tab title="脚本编写" %}

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

public class SessionStatusMonitor : MonoBehaviour
{
    private void OnEnable()
    {
        var manager = ConvaiManager.ActiveManager;
        if (manager == null) return;

        manager.Events.OnConnected    += HandleConnected;
        manager.Events.OnDisconnected += HandleDisconnected;
        manager.Events.OnSessionError += HandleError;
    }

    private void OnDisable()
    {
        var manager = ConvaiManager.ActiveManager;
        if (manager == null) return;

        manager.Events.OnConnected    -= HandleConnected;
        manager.Events.OnDisconnected -= HandleDisconnected;
        manager.Events.OnSessionError -= HandleError;
    }

    private void HandleConnected()             => Debug.Log("Session connected.");
    private void HandleDisconnected()          => Debug.Log("Session disconnected.");
    private void HandleError(SessionError err) => Debug.LogError($"[{err.ErrorCode}] {err.Message}");
}
```

{% endtab %}
{% endtabs %}

***

### `ConvaiSessionEventRelay` 事件

| 事件                                | 参数                                | 触发时机                                     |
| --------------------------------- | --------------------------------- | ---------------------------------------- |
| `OnConnected`                     | —                                 | 会话转换为 `Connected`                        |
| `OnDisconnected`                  | —                                 | 会话转换为 `Disconnected`                     |
| `OnReconnecting`                  | —                                 | 会话转换为 `Reconnecting`                     |
| `OnReconnected`                   | —                                 | 重新连接成功（从 `Reconnecting` 转换为 `Connected`) |
| `OnUsageLimitReached`             | —                                 | Convai 报告配额已耗尽                           |
| `OnUserIdleWarning`               | `UserIdleWarningRelayData`        | Convai 警告会话将因不活动而关闭                      |
| `OnUserIdleTimeout`               | `UserIdleTimeoutRelayData`        | 发出警告后，客户端空闲期限到期                          |
| `OnRuntimeBackgroundStateChanged` | `RuntimeBackgroundStateRelayData` | 应用程序的后台/前台状态或后台策略发生变化                    |
| `OnSessionStateChanged`           | `SessionStateChangedRelayData`    | 任意 `SessionState` 转换                     |
| `OnSessionError`                  | `SessionErrorRelayData`           | 会话遇到错误                                   |

### `SessionStateChangedRelayData` 字段

| 字段                         | 类型             | 说明                                |
| -------------------------- | -------------- | --------------------------------- |
| `OldState`                 | `SessionState` | 转换前的状态                            |
| `NewState`                 | `SessionState` | 转换后的状态                            |
| `SessionId`                | `string`       | 当前会话标识符                           |
| `ErrorCode`                | `string`       | 当新状态为 `Error`时的错误代码；否则为空          |
| `IsError`                  | `bool`         | 当 `NewState == Error`             |
| `IsReconnecting`           | `bool`         | 当状态从 `Connected` 到 `Reconnecting` |
| `IsConnectionEstablished`  | `bool`         | 从 `Connecting` 到 `Connected`      |
| `IsReconnectionSuccessful` | `bool`         | 从 `Reconnecting` 到 `Connected`    |
| `IsDisconnected`           | `bool`         | 当 `NewState == Disconnected`      |

### `SessionErrorRelayData` 字段

| 字段                  | 类型                  | 说明                               |
| ------------------- | ------------------- | -------------------------------- |
| `ErrorCode`         | `string`            | 分层错误代码，例如 `"connection.timeout"` |
| `Message`           | `string`            | 便于用户理解的错误描述                      |
| `SessionId`         | `string`            | 发生错误时的会话标识符                      |
| `IsRecoverable`     | `bool`              | 如果 SDK 可以尝试自动重新连接，则为 True        |
| `Stage`             | `SessionErrorStage` | 错误发生时所处的大致生命周期阶段                 |
| `HttpStatusCode`    | `int`               | 如果错误来自 HTTP 响应，则为 HTTP 状态码；否则为 0 |
| `HasHttpStatusCode` | `bool`              | 当 `HttpStatusCode > 0`           |

### `UserIdleWarningRelayData` 字段

| 字段                 | 类型       | 说明                     |
| ------------------ | -------- | ---------------------- |
| `RemainingSeconds` | `int`    | Convai 因不活动而关闭会话前的剩余秒数 |
| `Message`          | `string` | 便于用户理解的警告消息            |

### `UserIdleTimeoutRelayData` 字段

有关 [空闲超时处理](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/core-concepts/session-lifecycle.md#idle-warnings-and-timeouts)，请参阅“会话生命周期”。

| 字段                     | 类型       | 说明                           |
| ---------------------- | -------- | ---------------------------- |
| `WarningReceivedAtUtc` | `string` | 启动此期限的空闲警告的 ISO 8601 UTC 时间戳 |
| `DeadlineUtc`          | `string` | 客户端空闲期限的 ISO 8601 UTC 时间戳    |

### `RuntimeBackgroundStateRelayData` 字段

有关后台策略的具体取值，请参阅 [应用程序后台策略](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/core-concepts/session-lifecycle.md#application-background-policy) 在会话生命周期中。

| 字段                     | 类型                        | 说明                                             |
| ---------------------- | ------------------------- | ---------------------------------------------- |
| `IsBackgrounded`       | `bool`                    | 应用当前处于后台时为 True                                |
| `RequestedPolicy`      | `RuntimeBackgroundPolicy` | 请求的策略                                          |
| `EffectivePolicy`      | `RuntimeBackgroundPolicy` | 实际应用的策略——可能与 `RequestedPolicy` 不同（当平台无法遵循该策略时） |
| `Reason`               | `RuntimePauseReason`      | 后台状态转换的原因                                      |
| `UsedPlatformFallback` | `bool`                    | 当 `EffectivePolicy` 与 `RequestedPolicy`        |

***

### 不同时为 True `C# 事件中心 —`

通过以下方式访问： `ConvaiManager.ActiveManager.Events`。在 `OnEnable`中订阅，在 `OnDisable`.

### 中取消订阅

| 事件                                  | 会话范围的事件                           | 触发时机                  |
| ----------------------------------- | --------------------------------- | --------------------- |
| `OnConnected`                       | —                                 | 会话达到 `Connected`      |
| `OnDisconnected`                    | —                                 | 会话达到 `Disconnected`   |
| `OnSessionStateChanged`             | `SessionStateChanged`             | 任意 `SessionState` 转换  |
| `OnSessionError`                    | `SessionError`                    | 会话遇到错误                |
| `OnPipelineError`                   | `SessionError`                    | 处理管线发生错误（区别于会话级错误）    |
| `OnUsageLimitReached`               | `UsageLimitReached`               | Convai 报告配额已耗尽        |
| `OnUserIdleWarningReceived`         | `UserIdleWarningReceived`         | Convai 警告会话将因不活动而关闭   |
| `OnUserIdleTimeoutElapsed`          | `UserIdleTimeoutElapsed`          | 发出警告后，客户端空闲期限到期       |
| `OnRuntimeBackgroundStateChanged`   | `RuntimeBackgroundStateChanged`   | 应用程序的后台/前台状态或后台策略发生变化 |
| `OnParticipantJoined`               | `ParticipantInfo`                 | 参与者加入房间               |
| `OnParticipantLeft`                 | `ParticipantInfo`                 | 参与者离开房间               |
| `OnRoomOwnershipRebindStateChanged` | `RoomOwnershipRebindStateChanged` | 当前角色所有权重新绑定状态发生变化     |

以下领域事件的负载类型既支持上方的 C# Hub 事件，也支持本页前文中注明的中继数据类型。

### `SessionStateChanged`

| 字段          | 类型              | 说明                             |
| ----------- | --------------- | ------------------------------ |
| `OldState`  | `SessionState`  | 转换前的状态                         |
| `NewState`  | `SessionState`  | 转换后的状态                         |
| `SessionId` | `string`        | 会话标识符                          |
| `Timestamp` | `DateTime`      | 状态转换发生的 UTC 时间                 |
| `Error`     | `SessionError?` | 在以下情况下存在： `NewState == Error`  |
| `ErrorCode` | `string`        | 快捷访问 `Error?.ErrorCode`；无错误时为空 |

### `UsageLimitReached`

| 字段          | 类型         | 说明                               |
| ----------- | ---------- | -------------------------------- |
| `QuotaType` | `string`   | 已耗尽的配额类型（例如 `"monthly_minutes"`) |
| `Message`   | `string`   | Convai 提供的易读描述                   |
| `Timestamp` | `DateTime` | 事件发生的 UTC 时间                     |

### `UserIdleWarningReceived`

| 字段                 | 类型         | 说明                     |
| ------------------ | ---------- | ---------------------- |
| `RemainingSeconds` | `int`      | Convai 因不活动而关闭会话前的剩余秒数 |
| `Message`          | `string`   | 便于用户理解的警告消息            |
| `Timestamp`        | `DateTime` | 事件发生的 UTC 时间           |

### `UserIdleTimeoutElapsed`

支持 `UserIdleTimeoutRelayData` （用于中继）。参见 [空闲警告和超时](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/core-concepts/session-lifecycle.md#idle-warnings-and-timeouts) （位于“会话生命周期”中），了解其与 `UserIdleWarningReceived`.

| 字段                  | 类型         | 说明                      |
| ------------------- | ---------- | ----------------------- |
| `WarningReceivedAt` | `DateTime` | 触发此截止时间的空闲警告到达时的 UTC 时间 |
| `DeadlineUtc`       | `DateTime` | 客户端空闲截止时间的 UTC 时间       |
| `Timestamp`         | `DateTime` | 客户端检测到截止时间已过的 UTC 时间    |

### `RuntimeBackgroundStateChanged`

支持 `RuntimeBackgroundStateRelayData` （用于中继）。参见 [应用程序后台策略](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/core-concepts/session-lifecycle.md#application-background-policy) （位于“会话生命周期”中），了解策略值。

| 字段                | 类型                        | 说明                             |
| ----------------- | ------------------------- | ------------------------------ |
| `IsBackgrounded`  | `bool`                    | 应用当前处于后台时为 True                |
| `RequestedPolicy` | `RuntimeBackgroundPolicy` | 请求的策略                          |
| `EffectivePolicy` | `RuntimeBackgroundPolicy` | 实际应用的策略——平台可能无法满足请求，因此实际策略可能不同 |
| `Reason`          | `RuntimePauseReason`      | 后台状态转换的原因                      |
| `Timestamp`       | `DateTime`                | 状态转换发生的 UTC 时间                 |

### `ParticipantInfo`

| 字段                | 类型                | 说明                  |
| ----------------- | ----------------- | ------------------- |
| `ParticipantId`   | `string`          | 参与者的唯一标识符           |
| `Identity`        | `string`          | 与此参与者关联的身份字符串       |
| `DisplayName`     | `string`          | 易读的显示名称             |
| `ParticipantType` | `ParticipantType` | 指明参与者是本地玩家、远程玩家还是角色 |
| `IsLocal`         | `bool`            | 本地玩家参与者为 True       |
| `IsMuted`         | `bool`            | 此参与者的音频静音时为 True    |

### `RoomOwnershipRebindStateChanged`

| 字段                     | 类型                          | 说明                    |
| ---------------------- | --------------------------- | --------------------- |
| `Outcome`              | `RoomOwnershipRebindStatus` | 重新绑定尝试的结果             |
| `HasPendingReconnect`  | `bool`                      | 需要重新连接才能完成重新绑定时为 True |
| `SessionState`         | `SessionState`              | 事件发生时的会话状态            |
| `ActiveCharacterId`    | `string`                    | 当前绑定到对话的角色 ID         |
| `RequestedCharacterId` | `string`                    | 请求重新绑定的角色 ID          |
| `Timestamp`            | `DateTime`                  | 事件发生的 UTC 时间          |
| `ReconnectRequired`    | `bool`                      | 当所有权变更需要重新连接会话时为 True |

***

### 支持类型

### `SessionState` 枚举

| 值                   | 说明                          |
| ------------------- | --------------------------- |
| `Disconnected` (0)  | 没有活动会话。初始状态，以及正常断开连接后的最终状态。 |
| `Connecting` (1)    | 正在尝试建立新会话。                  |
| `Connected` (2)     | 会话处于活动状态并接受输入。              |
| `Reconnecting` (3)  | 连接已丢失；SDK 正在尝试自动恢复连接。       |
| `Disconnecting` (4) | 正在正常关闭会话。                   |
| `Error` (5)         | 发生不可恢复的错误。除非显式重置，否则无法继续会话。  |

**扩展方法** （针对 `SessionState`):

| 方法                  | 返回 `true` 条件                                       |
| ------------------- | -------------------------------------------------- |
| `IsConnected()`     | 状态为 `Connected` 或 `Reconnecting`                   |
| `IsTransitioning()` | 状态为 `Connecting`, `Reconnecting`，或 `Disconnecting` |
| `IsStable()`        | 状态为 `Disconnected`, `Connected`，或 `Error`          |
| `CanAcceptInput()`  | 状态仅为 `Connected` 时                                 |

### `SessionErrorStage` 枚举

| 值                     | 说明                      |
| --------------------- | ----------------------- |
| `Unknown` (0)         | 无法确定错误阶段                |
| `Configuration` (1)   | 读取或应用 SDK 配置时发生错误       |
| `ConnectApi` (2)      | 设置 API 连接时发生错误          |
| `Transport` (3)       | 传输层（WebSocket、gRPC）发生错误 |
| `SessionRecovery` (4) | 尝试重新连接时发生错误             |
| `Runtime` (5)         | 活动会话期间发生错误              |

### `ParticipantType` 枚举

| 值                  | 说明           |
| ------------------ | ------------ |
| `Unknown` (0)      | 无法确定参与者类型    |
| `LocalPlayer` (1)  | 此客户端上的本地玩家   |
| `RemotePlayer` (2) | 多人游戏会话中的远程玩家 |
| `Character` (3)    | AI 角色        |

### `RoomOwnershipRebindStatus` 枚举

| 值                              | 说明                   |
| ------------------------------ | -------------------- |
| `DeferredUntilStartup` (0)     | 已将重新绑定加入队列；运行时启动后将应用 |
| `AppliedImmediately` (1)       | 重新绑定已应用，无需重新连接       |
| `PendingReconnect` (2)         | 重新绑定已暂存；需要重新连接才能生效   |
| `RejectedTransitionState` (3)  | 由于会话当前正在转换而被拒绝       |
| `RejectedInvalidOwnership` (4) | 由于请求的角色不是有效所有者而被拒绝   |

### `SessionError` 结构体

完整的错误详细信息类型，用作以下内容的参数： `OnSessionError` 和 `OnPipelineError` 在 C# hub 中，并通过以下内容公开： `SessionErrorRelayData` （在 relay 中）。

| 成员                  | 类型                  | 说明                                                             |
| ------------------- | ------------------- | -------------------------------------------------------------- |
| `ErrorCode`         | `string`            | 分层代码，例如 `"connection.timeout"`, `"transport.closed"`           |
| `Message`           | `string`            | 人类可读的说明                                                        |
| `SessionId`         | `string`            | 发生错误时的会话标识符                                                    |
| `Timestamp`         | `DateTime`          | 错误发生的 UTC 时间                                                   |
| `IsRecoverable`     | `bool`              | 当 SDK 将尝试自动恢复时为 True                                           |
| `Exception`         | `Exception`         | 底层异常（如果有）                                                      |
| `Stage`             | `SessionErrorStage` | 错误发生的生命周期阶段                                                    |
| `HttpStatusCode`    | `int?`              | API 层错误的 HTTP 状态码                                              |
| `Category`          | `string`            | 的第一部分 `ErrorCode` （例如 `"connection"` 在 `"connection.timeout"`) |
| `IsConnectionError` | `bool`              | 当 `ErrorCode` 以 `"connection."`                                |
| `IsSessionError`    | `bool`              | 当 `ErrorCode` 以 `"session."`                                   |
| `IsTransportError`  | `bool`              | 当 `ErrorCode` 以 `"transport."`                                 |
| `IsProtocolError`   | `bool`              | 当 `ErrorCode` 以 `"protocol."`                                  |
| `IsServerError`     | `bool`              | 当 `ErrorCode` 以 `"server."`                                    |

***

### 高级用法 — `ConvaiEvents.Raw` 事件中心

{% hint style="warning" %}
这是高级用法。对于所有常见场景，请使用 `ConvaiEvents` 上的类型化属性。
{% endhint %}

`ConvaiEvents.Raw` 公开了底层的 `IEventHub`，因此你可以订阅任何没有对应类型化属性的领域事件类型。此类属性可在 `ConvaiEvents`.

原始事件中心使用基于令牌的订阅模型。 **丢失令牌会导致内存泄漏。** — 中心会一直持有对适配器的引用，直到显式取消订阅。

```csharp
using Convai.Domain.DomainEvents.Session;
using Convai.Domain.EventSystem;
using UnityEngine;

public class RawHubExample : MonoBehaviour
{
    private SubscriptionToken _token;

    private void OnEnable()
    {
        var hub = ConvaiManager.ActiveManager?.Events?.Raw;
        if (hub == null) return;

        _token = hub.Subscribe<SessionStateChanged>(
            e => Debug.Log($"Raw hub: {e.OldState} → {e.NewState}"),
            EventDeliveryPolicy.MainThread);
    }

    private void OnDisable()
    {
        ConvaiManager.ActiveManager?.Events?.Raw?.Unsubscribe(_token);
        _token = default;
    }
}
```

**`EventDeliveryPolicy` 选项：**

| 值                 | 适用场景                                      |
| ----------------- | ----------------------------------------- |
| `MainThread` （默认） | 所有 Unity API 调用——在下一个 Unity `Update` 帧中交付 |
| `Background`      | 非 Unity 线程安全的日志记录或指标收集                    |
| `Immediate`       | 在发布事件的线程上同步交付（谨慎使用）                       |

***

### 使用示例

### 示例 1 — 断开连接时变暗的监考 HUD

在训练模拟中，监考员叠加层会在会话中断时变暗，让学员清楚地看到 AI 角色当前不可用。

```csharp
using Convai.Domain.DomainEvents.Session;
using Convai.Runtime.Facades;
using UnityEngine;

public class ProctorHUD : MonoBehaviour
{
    [SerializeField] private CanvasGroup _overlay;

    private void OnEnable()
    {
        var mgr = ConvaiManager.ActiveManager;
        if (mgr == null) return;
        mgr.Events.OnConnected           += OnConnected;
        mgr.Events.OnDisconnected        += OnDisconnected;
        mgr.Events.OnSessionStateChanged += OnSessionStateChanged;
    }

    private void OnDisable()
    {
        var mgr = ConvaiManager.ActiveManager;
        if (mgr == null) return;
        mgr.Events.OnConnected           -= OnConnected;
        mgr.Events.OnDisconnected        -= OnDisconnected;
        mgr.Events.OnSessionStateChanged -= OnSessionStateChanged;
    }

    private void OnConnected()    => SetAlpha(1f);
    private void OnDisconnected() => SetAlpha(0.3f);

    private void OnSessionStateChanged(SessionStateChanged e)
    {
        if (e.NewState == SessionState.Reconnecting)
            SetAlpha(0.6f);
    }

    private void SetAlpha(float a) => _overlay.alpha = a;
}
```

### 示例 2 — 带可恢复性分支的会话错误横幅

企业入职培训模拟会显示一个可关闭的错误横幅。可恢复的错误会显示“正在重新连接…”；不可恢复的错误则提示学员重新加载模块。

```csharp
using Convai.Domain.DomainEvents.Session;
using Convai.Runtime.Facades;
using TMPro;
using UnityEngine;

public class ErrorBanner : MonoBehaviour
{
    [SerializeField] private GameObject _bannerRoot;
    [SerializeField] private TMP_Text   _messageLabel;
    [SerializeField] private GameObject _reloadButton;

    private void OnEnable()  => ConvaiManager.ActiveManager?.Events.OnSessionError += ShowError;
    private void OnDisable() => ConvaiManager.ActiveManager?.Events.OnSessionError -= ShowError;

    private void ShowError(SessionError err)
    {
        _bannerRoot.SetActive(true);
        _messageLabel.text = err.IsRecoverable
            ? "Connection interrupted. Reconnecting…"
            : $"Session error: {err.Message}. Please reload the module.";
        _reloadButton.SetActive(!err.IsRecoverable);
    }
}
```

### 示例 3 — 空闲警告倒计时器

医疗培训模拟程序会在 Convai 警告会话即将关闭时显示倒计时，让学员有时间恢复会话，避免 AI 角色断开连接。

```csharp
using Convai.Domain.DomainEvents.Session;
using Convai.Runtime.Facades;
using System.Collections;
using TMPro;
using UnityEngine;

public class IdleCountdown : MonoBehaviour
{
    [SerializeField] private TMP_Text _countdownLabel;

    private Coroutine _countdown;

    private void OnEnable()  => ConvaiManager.ActiveManager?.Events.OnUserIdleWarningReceived += StartCountdown;
    private void OnDisable() => ConvaiManager.ActiveManager?.Events.OnUserIdleWarningReceived -= StartCountdown;

    private void StartCountdown(UserIdleWarningReceived e)
    {
        if (_countdown != null) StopCoroutine(_countdown);
        _countdown = StartCoroutine(CountdownRoutine(e.RemainingSeconds));
    }

    private IEnumerator CountdownRoutine(int seconds)
    {
        while (seconds > 0)
        {
            _countdownLabel.text = $"Session closes in {seconds}s";
            yield return new WaitForSeconds(1f);
            seconds--;
        }
        _countdownLabel.text = string.Empty;
    }
}
```

***

### 故障排查

| 症状                                                | 可能原因                                   | 解决方法                                                          |
| ------------------------------------------------- | -------------------------------------- | ------------------------------------------------------------- |
| `OnSessionError` 从未触发                             | 在尝试连接后才订阅，错过了该事件                       | 在 `OnEnable`中订阅，并确保它 `OnEnable` 在 `ConnectAsync`              |
| `ConvaiSessionEventRelay` 未调用回调                   | 未分配 Manager，且 `AutoResolveManager` 已关闭 | 启用 **自动解析管理器** ，或为 `ConvaiManager` 字段赋值                       |
| 会话无限期卡在 `Reconnecting` 状态                         | 服务器无法访问或已达到重试次数上限                      | 检查网络；监听 `OnSessionError` 事件 `IsRecoverable == false` 以检测终止性故障 |
| `OnConnected` 会触发，但 `CanAcceptInput()` 返回 `false` | 在转换过程中调用的状态检查                          | 评估 `CanAcceptInput()` 在 `OnConnected` 处理程序内部，而不是在 `Update`    |

***

### 后续步骤

接好会话事件后，转到 [角色事件](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/scripting-reference/character-events.md) 以响应语音、情绪和回合生命周期。如需通过脚本控制连接，请参阅 [ConvaiManager API](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/scripting-reference/convaimanager-api.md).


---

# 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/scripting-reference/session-events.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.
