> 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`的 SDK 方法，请参见 [通知系统参考](/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] -->|请求通知| B[NotificationHandler]
    B -->|通过 SONotificationGroup 解析| C[UINotificationController]
    C -->|3 个对象的池| D[UINotification]
    E[会话错误] -->|SONotificationErrorMap| A
    F[您的脚本] -->|请求通知| A
    G[运行时设置\nNotificationsEnabled=false] -->|RuntimeSettingsNotificationApplier| A
```

`IConvaiNotificationService` 是所有通知请求的唯一入口点。 `NotificationHandler` 使用以下项按 ID 解析通知资源： `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 | 通知                             |
| ------------- | --------- | ------------------------------ |
| `AUTH_FAILED` | `精确`      | `Notification_AuthError`       |
| `CONNECTION_` | `前缀`      | `Notification_ConnectionError` |
| `RATE_LIMIT`  | `精确`      | `Notification_RateLimit`       |

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

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

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

* 当前显示的任何通知都会立即关闭
* 后续的 `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 = Prefix`
* 将 `通知` 映射到一项资源，该资源的消息为“连接失败。请联系 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} 注册通知。”`                  | 通知 `Id` 脚本中的内容与以下项中的任何资源均不匹配： `SONotificationGroup`                     | 检查 `Id` 字段，该字段位于 `SONotification` 资源上，并更新组                                                                             |
| 控制台显示 `“[NotificationHandler] UINotificationController 为 null，无法显示通知。”` | 控制器引用丢失，或未在场景中找到                                                        | 验证 `NotificationSystem.prefab` 位于场景中                                                                                   |
| 已请求通知但未显示；控制台没有错误                                                       | 此通知的 10 秒冷却时间仍处于活动状态                                                    | 等待 10 秒，或使用具有唯一 `Id`                                                                                                   |
| 与设置面板交互后通知被禁用                                                           | 用户已将 **通知** 关闭                                                          | 通过设置面板或以下方式重新启用： `IConvaiRuntimeSettingsService.Apply(new ConvaiRuntimeSettingsPatch { NotificationsEnabled = true })` |
| 第 4 条通知未立即显示                                                            | 最多同时显示 3 条——第 4 条会排队                                                    | 这是预期行为——一旦活动通知关闭，它就会显示                                                                                                 |

### 下一步

部署通知系统后，您可以显示连接错误、场景事件和自定义警报，而不会中断 AI 对话。若要让用户控制是否显示通知，请连接设置面板。若要重新设计通知视觉样式，请参阅“自定义 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, and the optional `goal` 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>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
