> 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/settings-panel/runtime-settings-api.md).

# 运行时设置 API

IConvaiRuntimeSettingsService 参考文档——通过代码读取当前设置、应用补丁、响应变更并重置为默认值。

`IConvaiRuntimeSettingsService` 是内置设置面板下层的脚本接口。任何脚本都可以读取当前设置快照、以原子方式应用补丁并订阅变更事件，无需在场景中放置该面板。

通过以下方式访问该服务： `ConvaiManager`:

```csharp
ConvaiManager.ActiveManager.TryGetRuntimeSettingsService(out var settings);
```

### `IConvaiRuntimeSettingsService`

| 成员                                        | 类型                                           | 说明                                  |
| ----------------------------------------- | -------------------------------------------- | ----------------------------------- |
| `Current`                                 | `ConvaiRuntimeSettingsSnapshot`              | 包含所有当前设置值的不可变快照                     |
| `Changed`                                 | `event Action<ConvaiRuntimeSettingsChanged>` | 任何设置发生变化时触发                         |
| `Apply(ConvaiRuntimeSettingsPatch patch)` | `ConvaiRuntimeSettingsApplyResult`           | 以原子方式应用一个或多个设置。补丁中留空的字段 `null` 保持不变 |
| `ResetToDefaults()`                       | `ConvaiRuntimeSettingsApplyResult`           | 将所有设置重置为项目默认值                       |

### `ConvaiRuntimeSettingsSnapshot`

由以下成员返回的不可变结构体： `Current` 并包含在应用结果和变更事件中。所有字段均反映生成快照时的状态。

| 字段                            | 类型       | 说明                |
| ----------------------------- | -------- | ----------------- |
| `PlayerDisplayName`           | `string` | 当前玩家显示名称，在转录气泡中显示 |
| `TranscriptEnabled`           | `bool`   | 是否启用转录界面          |
| `NotificationsEnabled`        | `bool`   | 是否启用场景内通知弹窗       |
| `PreferredMicrophoneDeviceId` | `string` | 首选麦克风输入设备的设备 ID   |

### `ConvaiRuntimeSettingsPatch`

传递给 `Apply()`。任何留空的字段 `null` 在应用后都保持不变。

| 字段                            | 类型       | 说明                        |
| ----------------------------- | -------- | ------------------------- |
| `PlayerDisplayName`           | `string` | 设置新的玩家显示名称。 `null` = 不变   |
| `TranscriptEnabled`           | `bool?`  | 启用或禁用转录界面。 `null` = 不变    |
| `NotificationsEnabled`        | `bool?`  | 启用或禁用通知。 `null` = 不变      |
| `PreferredMicrophoneDeviceId` | `string` | 设置首选麦克风设备 ID。 `null` = 不变 |

### `ConvaiRuntimeSettingsApplyResult`

由以下成员返回： `Apply()` 和 `ResetToDefaults()`.

| 字段                  | 类型                                | 说明                                |
| ------------------- | --------------------------------- | --------------------------------- |
| `Success`           | `bool`                            | `true` 如果应用操作成功                   |
| `Snapshot`          | `ConvaiRuntimeSettingsSnapshot`   | 应用后的设置状态                          |
| `AppliedMask`       | `ConvaiRuntimeSettingsChangeMask` | 实际发生变化的字段的位掩码                     |
| `ValidationMessage` | `string`                          | 失败原因（当 `Success == false`时）。成功时为空 |

### `ConvaiRuntimeSettingsChanged`

传递给 `Changed` 订阅者的载荷。

| 字段         | 类型                                | 说明             |
| ---------- | --------------------------------- | -------------- |
| `Previous` | `ConvaiRuntimeSettingsSnapshot`   | 更改前的设置状态       |
| `Current`  | `ConvaiRuntimeSettingsSnapshot`   | 更改后的设置状态       |
| `Mask`     | `ConvaiRuntimeSettingsChangeMask` | 指示哪些字段发生更改的位掩码 |

### `ConvaiRuntimeSettingsChangeMask`

一个 `[Flags]` 枚举，用于 `AppliedMask` 和 `ConvaiRuntimeSettingsChanged.Mask`。使用按位与进行比较，以检测特定更改。

| 值                             | 说明        |
| ----------------------------- | --------- |
| `None`                        | 没有字段发生更改  |
| `PlayerDisplayName`           | 玩家显示名称已更改 |
| `TranscriptEnabled`           | 转录启用状态已更改 |
| `NotificationsEnabled`        | 通知启用状态已更改 |
| `PreferredMicrophoneDeviceId` | 麦克风选择已更改  |
| `All`                         | 所有字段      |

### 使用示例

#### 读取当前设置

```csharp
using Convai.Runtime.Components;
using Convai.Shared.Types;
using UnityEngine;

public class SettingsReader : MonoBehaviour
{
    private void Start()
    {
        if (ConvaiManager.ActiveManager.TryGetRuntimeSettingsService(out var settings))
        {
            ConvaiRuntimeSettingsSnapshot current = settings.Current;
            Debug.Log($"Player name: {current.PlayerDisplayName}");
            Debug.Log($"Transcript on: {current.TranscriptEnabled}");
        }
    }
}
```

#### 应用设置补丁

```csharp
if (ConvaiManager.ActiveManager.TryGetRuntimeSettingsService(out var settings))
{
    var result = settings.Apply(new ConvaiRuntimeSettingsPatch
    {
        PlayerDisplayName = "Dr. Kaan",
        TranscriptEnabled = true
    });

    if (!result.Success)
        Debug.LogWarning($"Settings apply failed: {result.ValidationMessage}");
}
```

#### 响应设置更改

```csharp
using Convai.Runtime.Components;
using Convai.Shared.Abstractions;
using Convai.Shared.Types;
using UnityEngine;

public class SettingsChangeReactor : MonoBehaviour
{
    private IConvaiRuntimeSettingsService _settings;

    private void OnEnable()
    {
        if (ConvaiManager.ActiveManager.TryGetRuntimeSettingsService(out _settings))
            _settings.Changed += OnSettingsChanged;
    }

    private void OnDisable()
    {
        if (_settings != null)
            _settings.Changed -= OnSettingsChanged;
    }

    private void OnSettingsChanged(ConvaiRuntimeSettingsChanged changed)
    {
        if ((changed.Mask & ConvaiRuntimeSettingsChangeMask.PreferredMicrophoneDeviceId) != 0)
        {
            Debug.Log($"麦克风已更改为：{changed.Current.PreferredMicrophoneDeviceId}");
            ApplyMicrophoneChange(changed.Current.PreferredMicrophoneDeviceId);
        }

        if ((changed.Mask & ConvaiRuntimeSettingsChangeMask.PlayerDisplayName) != 0)
        {
            UpdatePlayerNameDisplay(changed.Current.PlayerDisplayName);
        }
    }
}
```

#### 分析 — 跟踪设置更改

某培训平台会记录学员更改麦克风设备的情况，以便分析会话质量：

```csharp
private void OnSettingsChanged(ConvaiRuntimeSettingsChanged changed)
{
    if ((changed.Mask & ConvaiRuntimeSettingsChangeMask.PreferredMicrophoneDeviceId) != 0)
    {
        AnalyticsTracker.LogEvent("microphone_changed", new Dictionary<string, object>
        {
            { "previous", changed.Previous.PreferredMicrophoneDeviceId },
            { "current", changed.Current.PreferredMicrophoneDeviceId }
        });
    }
}
```

### 故障排查

| 症状                              | 可能原因            | 解决方法                                                                                      |
| ------------------------------- | --------------- | ----------------------------------------------------------------------------------------- |
| `Apply()` 返回 `Success == false` | 验证失败            | 检查 `result.ValidationMessage` 以了解原因                                                       |
| `Changed` 事件未触发                 | 尚未订阅，或在设置更改后才订阅 | 在 `OnEnable` 中订阅，并确保在会话开始前完成                                                              |
| `ResetToDefaults()` 未检查返回结果     | 忽略了返回值          | `ResetToDefaults()` 返回 `ConvaiRuntimeSettingsApplyResult` — 检查 `result.Success` 以确认重置是否成功 |

### 后续步骤

{% 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/6695eb978b08dbf5023b367d38af0912574c4f52" %}
[聊天和字幕模式](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/ui-and-presentation/transcript-ui/chat-and-subtitle-modes.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/settings-panel/runtime-settings-api.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.
