> 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/character-and-player-api.md).

# 角色和玩家 API

角色和玩家脚本组件参考文档，涵盖会话控制、语音、音频和注意力目标。

`ConvaiCharacter` 用于控制单个 AI 角色的会话、语音、远程音频、动态上下文和注意力目标。 `ConvaiPlayer` 表示本地人类参与者，并提供文本消息发送和身份配置功能。这两个组件均由以下对象拥有和跟踪： `ConvaiManager`.

***

### 访问组件

```csharp
// 通过 Inspector 字段访问（推荐）
[SerializeField] private ConvaiCharacter _character;

// 通过管理器所有权列表访问
var character = ConvaiManager.ActiveManager?.Characters[0];

// 通过管理器的活动对话目标访问
var active = ConvaiManager.ActiveManager?.ActiveConversationCharacter;

// 玩家
var player = ConvaiManager.ActiveManager?.Player;
```

***

### `ConvaiCharacter`

#### 返回的结果

| 属性                                | 类型                       | 访问项 | 说明                                         |
| --------------------------------- | ------------------------ | --- | ------------------------------------------ |
| `CharacterId`                     | `string`                 | 读取  | Convai 角色标识符                               |
| `CharacterName`                   | `string`                 | 读取  | 角色的显示名称                                    |
| `OwnerId`                         | `string`                 | 读取  | 所有者账户标识符                                   |
| `SessionState`                    | `SessionState`           | 读取  | 此单个角色当前的会话状态                               |
| `IsCharacterReady`                | `bool`                   | 读取  | 角色完成就绪握手后为 True                            |
| `IsSessionConnected`              | `bool`                   | 读取  | 此角色的会话处于 `Connected` 状态时为 True             |
| `IsInConversation`                | `bool`                   | 读取  | 此角色是当前活动对话目标时为 True                        |
| `IsSpeaking`                      | `bool`                   | 读取  | 角色正在输出音频时为 True                            |
| `IsRemoteAudioEnabled`            | `bool`                   | 读取  | 此角色的远程音频输出已启用时为 True                       |
| `CurrentEmotion`                  | `string`                 | 读取  | 最近从 Convai 接收的情绪标签                         |
| `CurrentEmotionIntensity`         | `int`                    | 读取  | 最近的情绪强度（1–3）                               |
| `ConfigurationSource`             | `ConvaiConfigSourceMode` | 读取  | 配置来自 Inspector 字段还是配置文件资源                  |
| `CharacterConfigAsset`            | `ConvaiCharacterProfile` | 读取  | 当 `ConfigurationSource` 为基于资源的配置时使用的配置文件资源 |
| `NameTagColor`                    | `Color`                  | 读取  | 此角色在 UI 中姓名标签使用的颜色                         |
| `EnableRemoteAudioOnStart`        | `bool`                   | 读取  | 是否在启动时启用远程音频输出                             |
| `EnableSessionResume`             | `bool`                   | 读取  | 重新连接后会话是否尝试恢复                              |
| `CharacterReadyTimeoutSeconds`    | `float`                  | 读/写 | 等待角色就绪握手的秒数，超时后停止等待                        |
| `InitialDynamicInfoText`          | `string`                 | 读取  | 会话开始时发送的动态上下文文本                            |
| `InitialDynamicInfoKeepInContext` | `bool`                   | 读取  | 初始动态上下文是否在多轮对话中持续保留                        |
| `ActionConfig`                    | `ConvaiActionConfig`     | 读取  | 此角色的操作配置                                   |
| `DynamicContext`                  | `IConvaiDynamicContext`  | 读取  | 动态上下文命令接口                                  |
| `NarrativeDesign`                 | `IConvaiNarrativeDesign` | 读取  | 叙事设计接口                                     |
| `IsInjected`                      | `bool`                   | 读取  | SDK 注入依赖项后为 true                           |

#### `ConvaiConfigSourceMode` 枚举

| 值        | 说明                                 |
| -------- | ---------------------------------- |
| `Inline` | 在 Inspector 中直接为组件设置的配置            |
| `Asset`  | 从 `ConvaiCharacterProfile` 资源加载的配置 |

#### 会话控制

| 方法                                                                                         | 返回                       | 说明                                                  |
| ------------------------------------------------------------------------------------------ | ------------------------ | --------------------------------------------------- |
| `StartConversationAsync(CancellationToken ct = default)`                                   | `IConvaiOperation<Unit>` | 为此角色启动对话会话                                          |
| `StopConversationAsync(CancellationToken ct = default)`                                    | `IConvaiOperation<Unit>` | 停止此角色的对话会话                                          |
| `WaitForCharacterReadyAsync(float? timeoutSeconds = null, CancellationToken ct = default)` | `IConvaiOperation<Unit>` | 等待角色完成就绪握手。请在 `StartConversationAsync` 之后、发送输入之前调用。 |
| `ResetAndRetryAsync(CancellationToken ct = default)`                                       | `IConvaiOperation<Unit>` | 重置角色的会话状态并重试初始化。出错后调用。                              |
| `Reset()`                                                                                  | `bool`                   | 同步重置本地会话状态。如果重置已应用，则返回 `true` 。                     |

```csharp
// 连接并等待角色就绪，然后再发送输入
var startOp = character.StartConversationAsync(destroyCancellationToken);
await startOp;
if (startOp.IsSuccessful)
{
    await character.WaitForCharacterReadyAsync(timeoutSeconds: 10f, destroyCancellationToken);
    Debug.Log("Character is ready for input.");
}
```

#### 语音控制

| 方法                    | 返回                       | 说明                          |
| --------------------- | ------------------------ | --------------------------- |
| `ToggleSpeech()`      | `void`                   | 切换角色的对话会话状态：断开连接时启动，已连接时停止。 |
| `ToggleSpeechAsync()` | `IConvaiOperation<Unit>` | 异步版本的 `ToggleSpeech`.       |

#### 远程音频控制

| 方法                                    | 返回     | 说明                                    |
| ------------------------------------- | ------ | ------------------------------------- |
| `SetRemoteAudioEnabled(bool enabled)` | `bool` | 设置是否在本地播放此角色的音频输出。若更改已应用，则返回 `true` 。 |
| `EnableRemoteAudio()`                 | `bool` | 启用此角色的音频输出。若已应用，则返回 `true` 。          |
| `DisableRemoteAudio()`                | `bool` | 禁用此角色的音频输出。若已应用，则返回 `true` 。          |
| `ToggleRemoteAudio()`                 | `void` | 切换此角色的音频输出状态。                         |

{% hint style="info" %}
针对单个角色的音频控制，可让你在多角色场景中将某个角色静音，例如在主讲师发言时将辅助讲师静音。若要静音麦克风（你的输入），请使用 `ConvaiManager.ActiveManager.Audio`.
{% endhint %}

#### 动态上下文与叙事

| 方法                                                                                          | 返回     | 说明                                              |
| ------------------------------------------------------------------------------------------- | ------ | ----------------------------------------------- |
| `DynamicContext.AddEvent(string text, ConvaiRespondMode reaction = ConvaiRespondMode.Auto)` | `void` | 向角色跟踪的动态上下文追加一个按时间顺序排列的事件，并暂存一个批量更新以发送给 Convai。 |
| `SendTrigger(string triggerName)`                                                           | `void` | 按名称调用已保存的叙事设计触发器。                               |
| `SendNarrativeEvent(string eventMessage)`                                                   | `void` | 发送内联叙事事件上下文，并让 Convai 自然地作出回应。                  |
| `UpdateTemplateKeys(Dictionary<string, string> templateKeys)`                               | `void` | 更新叙事设计模板键值，以便动态替换叙事变量。                          |

{% hint style="info" %}
`SendTrigger` 按名称触发叙事设计中已配置的触发器。 `SendNarrativeEvent` 发送你在代码中编写的内联消息。请根据事件文本的编写位置选择合适的方法。
{% endhint %}

#### 注意力与操作

| 方法                                                                                                                               | 返回                         | 说明                          |
| -------------------------------------------------------------------------------------------------------------------------------- | -------------------------- | --------------------------- |
| `DynamicContext.SetCurrentAttentionObject(object currentAttentionObject, ConvaiRespondMode reaction = ConvaiRespondMode.Silent)` | `void`                     | 通过名称或操作对象资源，设置角色当前关注的场景内对象。 |
| `DynamicContext.ClearCurrentAttentionObject(ConvaiRespondMode reaction = ConvaiRespondMode.Silent)`                              | `void`                     | 清除当前关注的场景内对象。               |
| `GetActionConfigSource()`                                                                                                        | `ConvaiActionConfigSource` | 返回此角色的操作配置源组件。              |

#### `ConvaiCharacter` 事件

在以下方法中订阅： `OnEnable`，在以下方法中取消订阅： `OnDisable`.

| 事件                            | 签名                                           | 触发时机                         |
| ----------------------------- | -------------------------------------------- | ---------------------------- |
| `OnTranscriptReceived`        | `Action<string, bool>`                       | 收到转录文本时。参数：text、isFinal。     |
| `OnSpeechStarted`             | `Action`                                     | 角色开始生成音频输出                   |
| `OnSpeechStopped`             | `Action`                                     | 角色停止生成音频输出                   |
| `OnTurnCompleted`             | `Action<bool>`                               | 角色的对话轮次结束。参数：wasInterrupted。 |
| `OnCharacterReady`            | `Action`                                     | 角色完成其就绪握手                    |
| `OnSessionStateChanged`       | `Action<SessionState>`                       | 此角色的独立会话状态发生变化               |
| `OnEmotionChanged`            | `Action<string, int>`                        | 情绪发生变化。参数：情绪标签、原始强度（1–3）。    |
| `OnActionsReceived`           | `Action<IReadOnlyList<ConvaiActionCommand>>` | Convai 为此角色发送场景内操作命令         |
| `OnRemoteAudioEnabledChanged` | `Action<bool>`                               | 此角色的远程音频输出已启用或禁用             |

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

public class CharacterSessionMonitor : MonoBehaviour
{
    [SerializeField] private ConvaiCharacter _character;

    private void OnEnable()
    {
        _character.OnSessionStateChanged      += OnStateChanged;
        _character.OnRemoteAudioEnabledChanged += OnAudioChanged;
        _character.OnCharacterReady            += OnReady;
    }

    private void OnDisable()
    {
        _character.OnSessionStateChanged      -= OnStateChanged;
        _character.OnRemoteAudioEnabledChanged -= OnAudioChanged;
        _character.OnCharacterReady            -= OnReady;
    }

    private void OnStateChanged(SessionState state) =>
        Debug.Log($"[{_character.CharacterName}] session state: {state}");

    private void OnAudioChanged(bool enabled) =>
        Debug.Log($"[{_character.CharacterName}] audio output: {(enabled ? "on" : "off")}");

    private void OnReady() =>
        Debug.Log($"[{_character.CharacterName}] ready.");
}
```

***

### `ConvaiPlayer`

`ConvaiPlayer` 表示会话中的本地人类参与者。它负责管理玩家的显示名称和身份，并提供发送文本消息的功能。

#### 返回的结果

| 属性             | 类型       | 访问项 | 说明                 |
| -------------- | -------- | --- | ------------------ |
| `PlayerName`   | `string` | 读取  | 玩家的显示名称            |
| `PlayerId`     | `string` | 读取  | 玩家身份标识符            |
| `NameTagColor` | `Color`  | 读取  | 在 UI 中用于此玩家名称标签的颜色 |

#### 方法

| 方法                                                     | 返回     | 说明                                                     |
| ------------------------------------------------------ | ------ | ------------------------------------------------------ |
| `SendTextMessage(string message)`                      | `void` | 以当前玩家的身份向 Convai 发送文本消息，绕过麦克风输入。适用于文本输入模式或以编程方式控制玩家对话。 |
| `Configure(string playerName, string playerId = null)` | `void` | 设置玩家的显示名称和可选身份。请在调用 `ConnectAsync` 之前调用，以确保会话使用该身份。    |
| `SetRuntimeDisplayName(string displayName)`            | `void` | 在运行时更新玩家的显示名称，而不更改身份。此更改会反映在转录文本的参与者名称中。               |

#### `ConvaiPlayer` 事件

| 事件                  | 签名               | 触发时机                 |
| ------------------- | ---------------- | -------------------- |
| `OnTextMessageSent` | `Action<string>` | 通过 `SendTextMessage` |

```csharp
using Convai.Runtime.Facades;
using TMPro;
using UnityEngine;

public class TextInputController : MonoBehaviour
{
    [SerializeField] private TMP_InputField _inputField;

    public void OnSubmit()
    {
        var text = _inputField.text.Trim();
        if (string.IsNullOrEmpty(text)) return;

        ConvaiManager.ActiveManager?.Player?.SendTextMessage(text);
        _inputField.text = string.Empty;
    }
}
```

***

### 用法示例

#### 示例 1 — 连接角色并等待其就绪

医疗培训模拟程序会确保 AI 医生角色完全就绪后再开始评估，避免学员与尚未初始化的角色交谈。

```csharp
using Convai.Runtime.Components;
using Convai.Runtime.Core.Async;
using UnityEngine;

public class AssessmentStarter : MonoBehaviour
{
    [SerializeField] private ConvaiCharacter _physician;
    [SerializeField] private GameObject      _startPanel;

    private async void Start()
    {
        _startPanel.SetActive(false);

        var startOp = _physician.StartConversationAsync(destroyCancellationToken);
        await startOp;
        if (!startOp.IsSuccessful)
        {
            Debug.LogError($"Character connect failed: {startOp.Error.Message}");
            return;
        }

        var readyOp = _physician.WaitForCharacterReadyAsync(
            timeoutSeconds: 15f, destroyCancellationToken);
        await readyOp;

        if (readyOp.IsSuccessful)
            _startPanel.SetActive(true);
        else
            Debug.LogWarning("Character ready timeout — check your API key and network.");
    }
}
```

#### 示例 2 — 在多 NPC 场景中单独切换每个角色的音频

企业入职培训模拟程序中有三位 AI 顾问。UI 面板允许学员单独将任意一位顾问静音，而不影响其他顾问。

```csharp
using Convai.Runtime.Components;
using UnityEngine;
using UnityEngine.UI;

public class AdvisorMuteButton : MonoBehaviour
{
    [SerializeField] private ConvaiCharacter _advisor;
    [SerializeField] private Button         _muteButton;
    [SerializeField] private Sprite         _mutedIcon;
    [SerializeField] private Sprite         _unmutedIcon;

    private Image _buttonImage;

    private void Awake() => _buttonImage = _muteButton.GetComponent<Image>();

    private void OnEnable()
    {
        _muteButton.onClick.AddListener(OnToggleMute);
        _advisor.OnRemoteAudioEnabledChanged += RefreshIcon;
        RefreshIcon(_advisor.IsRemoteAudioEnabled);
    }

    private void OnDisable()
    {
        _muteButton.onClick.RemoveListener(OnToggleMute);
        _advisor.OnRemoteAudioEnabledChanged -= RefreshIcon;
    }

    private void OnToggleMute() => _advisor.ToggleRemoteAudio();

    private void RefreshIcon(bool enabled) =>
        _buttonImage.sprite = enabled ? _unmutedIcon : _mutedIcon;
}
```

#### 示例 3 — 无障碍文本输入模式

工业安全模拟程序为无法使用或受到限制的麦克风环境提供文本输入备用方案。

```csharp
using Convai.Runtime.Facades;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class AccessibilityTextInput : MonoBehaviour
{
    [SerializeField] private TMP_InputField _inputField;
    [SerializeField] private Button        _submitButton;

    private void OnEnable()  => _submitButton.onClick.AddListener(Submit);
    private void OnDisable() => _submitButton.onClick.RemoveListener(Submit);

    private void Submit()
    {
        var text = _inputField.text.Trim();
        if (string.IsNullOrEmpty(text)) return;

        var player = ConvaiManager.ActiveManager?.Player;
        if (player == null) return;

        player.SendTextMessage(text);
        _inputField.text = string.Empty;
        _inputField.ActivateInputField(); // 保持焦点，以便快速输入
    }
}
```

***

### 故障排查

| 症状                                 | 可能原因                                          | 解决方法                                                                                 |
| ---------------------------------- | --------------------------------------------- | ------------------------------------------------------------------------------------ |
| `WaitForCharacterReadyAsync` 超时    | 角色始终未收到 Convai 发来的就绪确认                        | 验证 API 密钥并检查网络；请在 `StartConversationAsync` 成功后调用，不要提前调用                              |
| `DynamicContext.AddEvent` 没有明显效果   | 调用时角色尚未进入对话，因此事件暂存在本地，尚未发送                    | 暂存的事件会在 `WaitForCharacterReadyAsync` 完成后自动发送； `DynamicContext.Flush()` 也只有在进入对话后才会发送 |
| `ToggleRemoteAudio()` 没有效果         | `EnableRemoteAudioOnStart` 为 `false` ，且从未启用音频 | 先调用 `EnableRemoteAudio()` 激活音频，然后再切换                                                 |
| `SendTextMessage` 已发送，但角色没有响应      | 会话不处于 `Connected` 状态                          | 发送前检查 `character.IsSessionConnected` 的值                                              |
| `OnActionsReceived` 已触发，但场景内没有动作执行 | `ConvaiActionDispatcher` 不在场景中，或操作名称不匹配       | 确认场景中存在 dispatcher；操作名称不区分大小写，但必须与配置的名称一致                                            |

***

### 后续步骤

有关房间级别的音频和麦克风控制，请参阅 [音频 API](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/scripting-reference/audio-api.md)。有关会话连接控制，请参阅 [ConvaiManager API](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/scripting-reference/convaimanager-api.md)。有关通过 relay 或 C# hub 订阅角色事件的信息，请参阅 [角色事件](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/scripting-reference/character-events.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/character-and-player-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.
