> 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/ui-and-presentation/notification-system.md).

# 通知系统

添加会自动显示会话错误的 Toast 式提醒，并使用通知资源在代码中触发场景内提醒。

通知系统会在场景中显示短暂的 Toast 式弹出通知。它会自动处理会话错误警报——当 Convai 报告连接或身份验证错误时，系统会将错误代码映射到通知资源，并将其加入显示队列。你也可以在会话期间随时通过代码触发自定义通知。

屏幕上最多可同时显示三条通知。其他通知会在内部排队，并在有空位时显示。

有关以下内容的字段级参考： `SONotification`, `SONotificationGroup`, `UINotificationController`和 `SONotificationErrorMap`，请参阅 [通知系统参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/ui-and-presentation/notification-system/notification-system-reference.md).

### 通知系统的工作原理

下图展示了系统的数据流：

```mermaid
graph TD
    A[IConvaiNotificationService] -->|RequestNotification| B[NotificationHandler]
    B -->|resolves via SONotificationGroup| C[UINotificationController]
    C -->|pool of 3| D[UINotification]
    E[Session error] -->|SONotificationErrorMap| A
    F[Your script] -->|RequestNotification| A
    G[Runtime settings\nNotificationsEnabled=false] -->|RuntimeSettingsNotificationApplier| A
```

`IConvaiNotificationService` 是所有通知请求的统一入口。 `NotificationHandler` 会使用 `SONotificationGroup`按 ID 查找通知资源，然后将其传递给 `UINotificationController`，由后者管理可重复使用的 `UINotification` 元素池。会话错误会经由 `SONotificationErrorMap` 自动将错误代码映射到通知资源。

### 将通知系统添加到场景

{% stepper %}
{% step %}

#### 创建通知资源

为每种警报类型创建一个 `SONotification` 资源。为每个资源指定唯一的 `Id` 字符串，使其与错误映射或脚本中引用的值相匹配。
{% endstep %}

{% step %}

#### 创建并填充通知组

创建一个 `SONotificationGroup` 资源。将所有 `SONotification` 资源添加到其 `soNotifications` 数组中。保存到 `Assets/Resources/SONotificationGroup.asset`.
{% endstep %}

{% step %}

#### 添加 NotificationSystem 预制体

将 `NotificationSystem.prefab` 拖入场景中。可在此处找到它： `Prefabs/Notifications/NotificationSystem.prefab` 包中。 <code class="expression">space.vars.sdk\_package\_id</code> 此预制件包含 `NotificationHandler` 和 `UINotificationController`.

在 `NotificationHandler`的 Inspector 中，将你的 `SONotificationGroup` 资源分配给 `notificationGroup` 字段。
{% endstep %}

{% step %}

#### 配置时序（可选）

调整 `UINotificationController` Inspector 字段，以匹配项目的视觉节奏。默认值适合作为大多数场景的起点。

设置正确后，触发通知会使面板从 `activeNotificationPos`滑入。滑入动画持续 `slipDuration` 秒（默认 `0.3`秒）。
{% endstep %}
{% endstepper %}

### 从代码触发通知

通过 `IConvaiNotificationService` 访问 `ConvaiManager`:

```csharp
using Convai.Runtime.Components;
using Convai.Runtime.Presentation.Views.Notifications;
using UnityEngine;

public class ScenarioNotifier : MonoBehaviour
{
    [SerializeField] private SONotification _stepCompleteNotification;
    [SerializeField] private SONotification _failureNotification;

    public void NotifyStepComplete()
    {
        if (ConvaiManager.ActiveManager.TryGetNotificationService(out var service))
            service.RequestNotification(_stepCompleteNotification);
    }

    public void NotifyFailure()
    {
        if (ConvaiManager.ActiveManager.TryGetNotificationService(out var service))
            service.RequestNotification(_failureNotification);
    }

    public void DismissAll()
    {
        if (ConvaiManager.ActiveManager.TryGetNotificationService(out var service))
            service.DismissNotification();
    }
}
```

`DismissNotification()` 会立即清除所有当前显示的通知，包括正在进行的动画。

{% hint style="info" %}
通知服务会对每个通知 **强制执行 10 秒冷却时间** ，以其 `Id`为单位。10 秒内的重复请求会被静默丢弃。这可以防止错误通知泛滥并占满屏幕。冷却时间会在 10 秒后自动重置。
{% endhint %}

### 自动将错误映射为通知

会话错误会通过 `SONotificationErrorMap`自动触发通知。此资源会将错误代码字符串映射到 `SONotification` 使用有序规则列表匹配资源。 **以第一个匹配的规则为准**.

**创建：** 右键单击 → **创建 → Convai → Notification System → Session Error Map**

保存到 `Assets/Resources/SONotificationErrorMap.asset` 以便自动加载。

如需查看完整的 `SessionErrorNotificationRule` 字段引用，请参阅 [通知系统参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/ui-and-presentation/notification-system/notification-system-reference.md).

**规则配置示例：**

| 错误模式          | 匹配类型     | 通知                             |
| ------------- | -------- | ------------------------------ |
| `AUTH_FAILED` | `Exact`  | `Notification_AuthError`       |
| `CONNECTION_` | `Prefix` | `Notification_ConnectionError` |
| `RATE_LIMIT`  | `Exact`  | `Notification_RateLimit`       |

规则按从上到下的顺序进行评估。将更具体的规则放在更宽泛的前缀匹配规则上方。

### 遵循通知运行时设置

通知系统会遵循 **通知** 内置设置面板中的开关。当用户关闭通知时：

* 当前显示的任何通知都会立即消失
* 后续 `RequestNotification` 调用会被静默忽略
* 日志会记录： `"Cannot send notification because notifications are disabled in runtime settings."`

从脚本中切换通知开关：

```csharp
if (ConvaiManager.ActiveManager.TryGetRuntimeSettingsService(out var settings))
{
    settings.Apply(new ConvaiRuntimeSettingsPatch { NotificationsEnabled = false });
}
```

### 使用示例

#### 企业入职引导 — 步骤完成提醒

在企业入职培训模拟中，每当受训者与 AI 人力资源代表完成一个必需的对话检查点时，系统都会通知他们：

* 创建一个 `SONotification` 资源，设置 `Id = "checkpoint-complete"`，并使用勾选图标和消息“检查点已完成。请继续下一个话题。”
* 调用 `service.RequestNotification(checkpointNotification)` ，在检查点评估处理程序中执行该调用
* 通知显示 4 秒后自动消失，不会中断正在进行的对话
* 10 秒冷却时间可防止评估逻辑多次触发时重复发送通知

在运行时，每完成一个检查点都会显示一条简短确认消息，随后自动消失，不会暂停对话。

#### 防火墙受限环境中的连接错误

在企业网络上运行的培训模拟需要在连接失败时显示有用的错误消息：

* 创建一个 `SONotificationErrorMap` 并添加以下规则： `ErrorPattern = "CONNECTION_"`, `MatchType = Prefix`
* 将 `Notification` 设置为包含以下消息的资源：“连接失败。请拨打分机 4400 联系 IT 支持。”
* 错误映射会自动处理任何以 `CONNECTION_` 为前缀的错误，无需编写额外代码

在运行时，任何连接失败都会触发清晰且可采取行动的通知，而不是悄无声息地失败。

#### 多场景重置——场景切换时清除所有通知

多场景模拟在场景切换时会清除所有未消失的通知：

```csharp
public void TransitionToNextScenario()
{
    if (ConvaiManager.ActiveManager.TryGetNotificationService(out var service))
        service.DismissNotification();

    LoadNextScenario();
}
```

在运行时，调用 `DismissNotification()` 会立即清空屏幕，然后加载下一个场景，确保过期提示不会出现在错误的场景中。

### 故障排查

| 症状                                                                                                                            | 可能原因                                                                   | 解决方法                                                                                                                 |
| ----------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| 没有显示通知；控制台显示 `"[NotificationHandler] SONotificationGroup asset could not be resolved."`                                       | 组资源不在 `Resources/`                                                     | 请保存到 `Assets/Resources/SONotificationGroup.asset`                                                                    |
| 控制台显示 `"[NotificationHandler] No UINotificationController found and no prefab set."`                                          | `场景中没有` NotificationSystem.prefab `，且未分配` notificationControllerPrefab | 将预制件添加到场景中，或在 `NotificationHandler` 检查器中分配控制器预制件                                                                     |
| 控制台显示 `"[NotificationHandler] Notification service not available; notifications will be deferred until services initialize."` | 通知在 `ConvaiManager` 完成初始化之前触发                                          | 将通知调用延迟到 `ConvaiManager.IsInitialized` 为 `true`                                                                      |
| 时 `"[NotificationHandler] No notification registered in the notification group for id: {id}"`                                 | 通知 `Id` 脚本中的值与 `SONotificationGroup`                                   | 检查 `Id` 字段是否与 `SONotification` 资源中的值匹配，并更新组                                                                          |
| 控制台显示 `"[NotificationHandler] UINotificationController is null, cannot display notification."`                                | 控制器引用已丢失，或在场景中找不到                                                      | 确认 `NotificationSystem.prefab` 位于场景中                                                                                 |
| 已请求通知，但未显示；控制台没有错误                                                                                                            | 此通知处于 10 秒冷却期                                                          | 等待 10 秒，或使用具有唯一 `Id`                                                                                                 |
| 与设置面板交互后，通知已停用                                                                                                                | 用户已将 **通知** 关闭                                                         | 通过设置面板重新启用，或调用 `IConvaiRuntimeSettingsService.Apply(new ConvaiRuntimeSettingsPatch { NotificationsEnabled = true })` |
| 第 4 条通知没有立即显示                                                                                                                 | 最多同时显示 3 条——第 4 条会进入队列                                                 | 这是预期行为——活动通知关闭后，它就会显示                                                                                                |

### 后续步骤

部署通知系统后，你可以显示连接错误、场景事件和自定义提醒，而不会打断 AI 对话。若要让用户控制是否显示通知，请接入设置面板。若要调整通知的视觉样式，请参阅“自定义 UI 组件”。

{% content-ref url="/pages/dddf624ca0ae7ec32afa0c9e601f2cb7c7ab2b6a" %}
[设置面板](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/ui-and-presentation/settings-panel.md)
{% endcontent-ref %}

{% content-ref url="/pages/5f60eaa8d444f5ee8a995392852da827736d3b54" %}
[自定义 UI 组件](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/ui-and-presentation/customizing-ui-components.md)
{% endcontent-ref %}

{% content-ref url="/pages/caa7ca5d0d83b53a1e0bc946efa57288e237a693" %}
[通知系统参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/ui-and-presentation/notification-system/notification-system-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/ui-and-presentation/notification-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.
