> 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 事件上触发——请根据代码需求选择。有关中继组件以及何时选择每种方式的概念概述，请参阅 [事件系统](/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： **添加组件 → Convai → Events → Convai Session Event Relay**.
2. 分配一个 `ConvaiManager` 引用到 **Manager** 字段，或将其留空并启用 **自动解析 Manager** 以在运行时使用 `ConvaiManager.ActiveManager` 。
3. 在 Inspector 中每个事件下连接您的回调。

{% hint style="warning" %}
**自动解析 Manager** 很方便，但不具确定性。对于具有多个 `ConvaiManager` 实例的场景，请显式分配目标 Manager。
{% 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("会话已连接。");
    private void HandleDisconnected()          => Debug.Log("会话已断开。");
    private void HandleError(SessionError err) => Debug.LogError($"[{err.ErrorCode}] {err.Message}");
}
```

{% endtab %}
{% endtabs %}

***

### `ConvaiSessionEventRelay` 事件

| 事件                                | 参数                                | 触发时机                      |
| --------------------------------- | --------------------------------- | ------------------------- |
| `OnConnected`                     | —                                 | 会话转换为 `已连接`               |
| `OnDisconnected`                  | —                                 | 会话转换为 `已断开连接`             |
| `OnReconnecting`                  | —                                 | 会话转换为 `重新连接中`             |
| `OnReconnected`                   | —                                 | 重连成功（转换自 `重新连接中` 为 `已连接`) |
| `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`         | 在以下情况下为 True： `NewState == Error`        |
| `IsReconnecting`           | `bool`         | 从以下状态转换时为 True： `已连接` 为 `重新连接中`          |
| `IsConnectionEstablished`  | `bool`         | 从以下状态转换时为 True： `连接中` 为 `已连接`            |
| `IsReconnectionSuccessful` | `bool`         | 从以下状态转换时为 True： `重新连接中` 为 `已连接`          |
| `IsDisconnected`           | `bool`         | 在以下情况下为 True： `NewState == Disconnected` |

### `SessionErrorRelayData` 字段

| 字段                  | 类型                  | 说明                                 |
| ------------------- | ------------------- | ---------------------------------- |
| `ErrorCode`         | `string`            | 分层错误代码，例如 `"connection.timeout"`   |
| `Message`           | `string`            | 人类可读的错误描述                          |
| `SessionId`         | `string`            | 发生错误时的会话标识符                        |
| `IsRecoverable`     | `bool`              | 如果 SDK 可以自动尝试重连，则为 True            |
| `Stage`             | `SessionErrorStage` | 错误产生时所处的广义生命周期阶段                   |
| `HttpStatusCode`    | `int`               | 如果错误来自 HTTP 响应，则为 HTTP 状态代码；否则为 0  |
| `HasHttpStatusCode` | `bool`              | 在以下情况下为 True： `HttpStatusCode > 0` |

### `UserIdleWarningRelayData` 字段

| 字段                 | 类型       | 说明                     |
| ------------------ | -------- | ---------------------- |
| `RemainingSeconds` | `int`    | Convai 因无活动而关闭会话前的剩余秒数 |
| `Message`          | `string` | 人类可读的警告消息              |

### `UserIdleTimeoutRelayData` 字段

关于 [空闲超时处理](/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` 字段

有关后台策略值本身，请参阅 [应用程序后台策略](/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`                    | 在以下情况下为 True： `EffectivePolicy` 不同于 `RequestedPolicy` |

***

### C# 事件中心 — `ConvaiEvents`

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

### 会话范围事件

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

以下领域事件负载类型支持上面的 C# 中心事件，以及本页前面注明的中继数据类型。

### `SessionStateChanged`

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

### `UsageLimitReached`

| 字段          | 类型         | 说明                               |
| ----------- | ---------- | -------------------------------- |
| `QuotaType` | `string`   | 耗尽的是哪种配额（例如 `"monthly_minutes"`) |
| `Message`   | `string`   | 来自 Convai 的人类可读描述                |
| `时间戳`       | `DateTime` | 事件的 UTC 时间                       |

### `UserIdleWarningReceived`

| 字段                 | 类型         | 说明                     |
| ------------------ | ---------- | ---------------------- |
| `RemainingSeconds` | `int`      | Convai 因无活动而关闭会话前的剩余秒数 |
| `Message`          | `string`   | 人类可读的警告消息              |
| `时间戳`              | `DateTime` | 事件的 UTC 时间             |

### `UserIdleTimeoutElapsed`

支持 `UserIdleTimeoutRelayData` 在中继上。请参阅 [空闲警告和超时](/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 时间       |
| `时间戳`               | `DateTime` | 客户端观察到截止时间到期的 UTC 时间    |

### `RuntimeBackgroundStateChanged`

支持 `RuntimeBackgroundStateRelayData` 在中继上。请参阅 [应用程序后台策略](/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`      | 发生后台转换的原因                  |
| `时间戳`             | `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         |
| `时间戳`                  | `DateTime`                  | 事件的 UTC 时间           |
| `ReconnectRequired`    | `bool`                      | 所有权更改需要重新连接会话时为 True |

***

### 支持类型

### `SessionState` 枚举

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

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

| 方法                  | 返回 `true` 当                   |
| ------------------- | ----------------------------- |
| `IsConnected()`     | 状态为 `已连接` 或 `重新连接中`           |
| `IsTransitioning()` | 状态为 `连接中`, `重新连接中`，或 `正在断开连接` |
| `IsStable()`        | 状态为 `已断开连接`, `已连接`，或 `Error`  |
| `CanAcceptInput()`  | 状态为 `已连接` 仅                   |

### `SessionErrorStage` 枚举

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

### `ParticipantType` 枚举

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

### `RoomOwnershipRebindStatus` 枚举

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

### `SessionError` 结构体

完整的错误详细信息类型，用作以下项的参数： `OnSessionError` 和 `OnPipelineError` 位于 C# 中心中，并通过以下项公开： `SessionErrorRelayData` 位于中继中。

| 成员                  | 类型                  | 说明                                                                 |
| ------------------- | ------------------- | ------------------------------------------------------------------ |
| `ErrorCode`         | `string`            | 分层代码，例如 `"connection.timeout"`, `"transport.closed"`               |
| `Message`           | `string`            | 人类可读的描述                                                            |
| `SessionId`         | `string`            | 发生错误时的会话标识符                                                        |
| `时间戳`               | `DateTime`          | 发生错误的 UTC 时间                                                       |
| `IsRecoverable`     | `bool`              | 当 SDK 将尝试自动恢复时为 True                                               |
| `异常`                | `异常`                | 底层异常（如有）                                                           |
| `Stage`             | `SessionErrorStage` | 错误产生时所处的生命周期阶段                                                     |
| `HttpStatusCode`    | `int?`              | API 层错误的 HTTP 状态代码                                                 |
| `类别`                | `string`            | 以下项的第一段： `ErrorCode` （例如 `"connection"` 来自 `"connection.timeout"`) |
| `IsConnectionError` | `bool`              | 在以下情况下为 True： `ErrorCode` 以以下内容开头： `"connection."`                 |
| `IsSessionError`    | `bool`              | 在以下情况下为 True： `ErrorCode` 以以下内容开头： `"session."`                    |
| `IsTransportError`  | `bool`              | 在以下情况下为 True： `ErrorCode` 以以下内容开头： `"transport."`                  |
| `IsProtocolError`   | `bool`              | 在以下情况下为 True： `ErrorCode` 以以下内容开头： `"protocol."`                   |
| `IsServerError`     | `bool`              | 在以下情况下为 True： `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($"原始中心：{e.OldState} → {e.NewState}"),
            EventDeliveryPolicy.MainThread);
    }

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

**`EventDeliveryPolicy` 选项：**

| 值                 | 使用时机                                    |
| ----------------- | --------------------------------------- |
| `MainThread` （默认） | 所有 Unity API 访问——在下一个 Unity `Update` 周期 |
| `背景`              | 非 Unity 线程安全的日志记录或指标                    |
| `立即`              | 在发布线程上同步传递（请谨慎使用）                       |

***

### 使用示例

### 示例 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
            ? "连接中断。正在重新连接…"
            : $"会话错误：{err.Message}。请重新加载模块。";
        _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 = $"会话将在 {seconds}s 后关闭";
            yield return new WaitForSeconds(1f);
            seconds--;
        }
        _countdownLabel.text = string.Empty;
    }
}
```

***

### 故障排除

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

***

### 下一步

会话事件接线完成后，转到 [角色事件](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/scripting-reference/character-events.md) 以响应语音、情感和轮次生命周期。有关脚本中的连接控制，请参见 [ConvaiManager API](/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.
