> 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 的弹出提示。它会自动处理会话错误警报——当 Convai 报告连接错误或身份验证错误时，系统会将错误代码映射到通知资源并排队显示。你也可以在会话中的任何时候从代码触发自定义通知。

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

关于以下内容的字段级参考 `SONotification`, `SONotificationGroup`, `UINotificationController`，以及 `SONotificationErrorMap`，请参见 [通知系统参考](/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 -->|通过 SONotificationGroup 解析| C[UINotificationController]
    C -->|3 个复用槽位| D[UINotification]
    E[会话错误] -->|SONotificationErrorMap| A
    F[你的脚本] -->|RequestNotification| A
    G[运行时设置\nNotificationsEnabled=false] -->|RuntimeSettingsNotificationApplier| A
```

`IConvaiNotificationService` 是所有通知请求的唯一入口。 `NotificationHandler` 使用 `SONotificationGroup`，然后传递给 `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 → 通知系统 → 会话错误映射**

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

有关完整的 `SessionErrorNotificationRule` 字段参考，请参见 [通知系统参考](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/ui-and-presentation/notification-system/notification-system-reference.md).

**示例规则配置：**

| ErrorPattern  | MatchType | Notification                   |
| ------------- | --------- | ------------------------------ |
| `AUTH_FAILED` | `精确`      | `Notification_AuthError`       |
| `CONNECTION_` | `前缀`      | `Notification_ConnectionError` |
| `RATE_LIMIT`  | `精确`      | `Notification_RateLimit`       |

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

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

通知系统会遵守内置 Settings Panel 中的 **Notifications** 切换开关。当用户禁用通知时：

* 任何当前显示的通知都会立即关闭
* 后续的 `RequestNotification` 调用会被静默忽略
* 日志会记录： `"无法发送通知，因为运行时设置中已禁用通知。"`

要通过脚本切换通知：

```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 = 前缀`
* 设置 `Notification` 映射到一个资源，该资源的消息为“连接失败。请联系 IT 支持，分机 4400。”
* 错误映射会在任何 `CONNECTION_` 以前缀开头的错误上自动触发——无需额外代码

在运行时，任何连接失败都会产生清晰、可操作的通知，而不是静默失败。

#### 多场景重置——在场景切换时关闭所有通知

多场景模拟在不同场景之间切换时会清除任何残留通知：

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

    LoadNextScenario();
}
```

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

### 故障排查

| 症状                                                                    | 可能原因                                                                  | 修复                                                                                                                        |
| --------------------------------------------------------------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| 不会出现任何通知；控制台显示 `"[NotificationHandler] 无法解析 SONotificationGroup 资源。"` | 组资源不在 `Resources/`                                                    | 保存到 `Assets/Resources/SONotificationGroup.asset`                                                                          |
| 控制台显示 `"[NotificationHandler] 未找到 UINotificationController 且未设置预制件。"` | `NotificationSystem.prefab` 不在场景中或 `notificationControllerPrefab` 未分配 | 将预制件添加到场景中，或在 `NotificationHandler` 检查器                                                                                   |
| 控制台显示 `"[NotificationHandler] 通知服务不可用；通知将在服务初始化后延迟处理。"`               | 通知在 `ConvaiManager` 完成初始化之前触发                                         | 将通知调用延迟到 `ConvaiManager.IsInitialized` 为 `true`                                                                           |
| 控制台显示 `"[NotificationHandler] 在通知组中未找到 id 为 {id} 的通知"`                | Notification `Id` 脚本中的值不匹配任何 `SONotificationGroup`                    | 请查看 `Id` 字段在 `SONotification` 资源，请更新该组                                                                                    |
| 控制台显示 `"[NotificationHandler] UINotificationController 为空，无法显示通知。"`   | 控制器引用丢失或未在场景中找到                                                       | 验证 `NotificationSystem.prefab` 位于场景中                                                                                      |
| 已请求通知但未显示；没有控制台错误                                                     | 该通知的 10 秒冷却期处于激活状态                                                    | 等待 10 秒，或使用一个具有唯一 `Id`                                                                                                    |
| 在 Settings Panel 交互后通知已禁用                                             | 用户切换了 **Notifications** 关闭                                            | 通过 Settings Panel 或 `IConvaiRuntimeSettingsService.Apply(new ConvaiRuntimeSettingsPatch { NotificationsEnabled = true })` |
| 第 4 条通知未立即显示                                                          | 最多同时 3 条——第 4 条已入队                                                    | 预期行为——一旦有活动通知关闭，它就会显示                                                                                                     |

### 下一步

有了通知系统，你可以在不打断 AI 对话的情况下展示连接错误、场景事件和自定义警报。要让用户控制是否显示通知，请连接 Settings Panel。要重新设计通知视觉效果，请参见自定义 UI 组件。

{% content-ref url="/pages/dddf624ca0ae7ec32afa0c9e601f2cb7c7ab2b6a" %}
[设置面板](/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 组件](/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" %}
[通知系统参考](/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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/ui-and-presentation/notification-system.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
