> 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/unity-plugin-beta-overview/features/emotion/scripting-api-reference.md).

# 脚本 API 参考

读取实时情绪状态、通过代码驱动表情、响应情绪事件，并在脚本序列期间将角色锁定到特定情绪。

## 情绪状态的运行时控制与观测

Emotion 系统提供两种不同的运行时情绪状态响应与控制方式。 **Inspector 方式** 使用 `ConvaiCharacterEventRelay` ——这个组件会将情绪变化回调作为标准 Unity Events 提供，无需编写代码。 **脚本方式** 使用 `ConvaiEmotionController` 可直接使用，提供完整的 C# API，用于读取实时状态、注入覆盖值以及锁定表情。两种方式可以同时使用。

## Inspector 方式 — ConvaiCharacterEventRelay

`ConvaiCharacterEventRelay` 是一个 MonoBehaviour，可将角色回调桥接到 Unity Events，让设计人员无需编写代码，即可完全通过 Inspector 配置情绪响应。

**添加组件：** **Convai → Events → Convai Character Event Relay**

将其放置在场景中的任意 GameObject 上。它会自动查找同一 GameObject 上的 `ConvaiCharacter` ，也可以通过 **Character** 字段指定另一个 GameObject 上的角色。

### Inspector 字段

| 字段                       | 默认值    | 说明                                                |
| ------------------------ | ------ | ------------------------------------------------- |
| `Character`              | *（无）*  | 可选：显式引用一个 `ConvaiCharacter`。留空则使用自动解析。            |
| `Auto Resolve Character` | `true` | 启用后，中继组件会自动查找同一 GameObject 上的 `ConvaiCharacter` 。 |

### OnEmotionChanged 事件

中继组件提供一个 **On Emotion Changed** Unity Event，每当角色的情绪信号发生变化时就会触发。该事件会提供一个 `CharacterEmotionRelayData` 负载：

| 属性              | 类型       | 说明                            |
| --------------- | -------- | ----------------------------- |
| `CharacterId`   | `string` | 角色的唯一标识符。                     |
| `CharacterName` | `string` | 角色的显示名称（若无则使用 GameObject 名称）。 |
| `Emotion`       | `string` | 服务器返回的原始标签（例如 `"happy"`).     |
| `Intensity`     | `int`    | 后端发送的 1–3 整数等级。               |

**配置示例：** 将 `ConvaiCharacterEventRelay` 添加到 NPC 的 GameObject。在 **On Emotion Changed** 列表中，点击 **+**，将 UI Text 组件拖到对象字段中，然后选择 `Text.text` ——每次情绪变化时，标签都会自动更新。

{% hint style="info" %}
`ConvaiCharacterEventRelay` 会在情绪分类解析或平滑处理之前，针对服务器返回的原始标签触发。可用于 UI 显示、音频提示或简单的分支逻辑。若要使用平滑处理后的解析状态（包含分数和保持时间），请使用 `ConvaiEmotionController.Current` 改为从脚本中执行。
{% endhint %}

## 脚本路径 — 访问控制器

该 `ConvaiEmotionController` 组件可以通过其具体类型或通过以下方式获取 `IEmotionStateSource` 接口。当你想让代码与特定组件的实现解耦时，请使用接口：

```csharp
using Convai.Modules.Emotion.Components;
using Convai.Domain.Embodiment.Interfaces;

// 具体类型 — 包含覆盖项和锁定项的完整 API 访问权限
var controller = npcGameObject.GetComponent<ConvaiEmotionController>();

// 接口 — 以解耦方式只读访问当前情绪读数
var source = npcGameObject.GetComponent<IEmotionStateSource>();
EmotionReading reading = source.Current;
```

## 读取当前情绪状态

`ConvaiEmotionController.Current` 返回一个 `EmotionReading` ——这是根据累加器的输出在每帧重新构建的不可变快照。你可以在 `Update` 中轮询它，也可以在任何事件发生时对其作出响应。

```csharp
using Convai.Domain.Embodiment.Readings;
using Convai.Modules.Emotion.Components;
using UnityEngine;

public sealed class EmotionLogger : MonoBehaviour
{
    [SerializeField] private ConvaiEmotionController emotionController;

    private void Update()
    {
        EmotionReading reading = emotionController.Current;

        if (!reading.IsNeutral)
            Debug.Log($"Dominant emotion: {reading.DominantLabel} ({reading.DominantScore:F2})");
    }
}
```

### EmotionReading 属性

| 属性                    | 类型                                   | 说明                                          |
| --------------------- | ------------------------------------ | ------------------------------------------- |
| `DominantLabel`       | `string`                             | 得分最高的情绪的规范标签（例如 `"joy"`, `"anger"`).        |
| `DominantScore`       | `float`                              | 主导情绪经过平滑处理和突发增强后的归一化分数 \[0–1]。              |
| `AllScores`           | `IReadOnlyDictionary<string, float>` | 按规范标签为键的完整分数表。分类体系中的每种情绪都有对应条目。             |
| `MouthInfluence`      | `float`                              | \[0–1] 提示值，供 LipSync 合成器在非说话帧期间混合嘴部形状。      |
| `DominantHoldSeconds` | `float`                              | 当前主导标签持续保持的实际时间（秒）。                         |
| `IsNeutral`           | `bool`                               | 当主导标签为 `"neutral"` 或者当 `DominantScore ≤ 0`. |
| `NeutralLabel`        | `const string`                       | 字符串常量 `"neutral"`.                          |

## 检查器锁定

该控制器有三个可序列化字段，可让你直接在检查器中将表情固定为特定情绪——这在创作和调试时很有用；如果你想在不进入播放模式的情况下，在场景视图中预览混合形状槽位的结果，也可以使用这些字段。

| 字段                   | 类型       | 默认值         | 说明                                  |
| -------------------- | -------- | ----------- | ----------------------------------- |
| `lockEmotion`        | `bool`   | `false`     | 启用后，将忽略所有传入的服务器情绪事件，角色会保持锁定的情绪。     |
| `lockedEmotionLabel` | `string` | `"neutral"` | 在以下功能启用期间保持的规范分类标签： `lockEmotion` 。 |
| `lockedIntensity`    | `float`  | `1.0`       | 锁定情绪的强度 \[0–1]。                     |

{% hint style="info" %}
`ConvaiEmotionController` 具有 `[ExecuteAlways]`特性。在 Inspector 中设置 `lockEmotion = true` 会立即更新 Scene 视图中的混合形状，无需进入 Play Mode。这是一个实用工具，可用于验证槽位映射是否能在角色网格上产生正确的视觉效果。
{% endhint %}

{% hint style="danger" %}
`lockEmotion` 是一个 **序列化字段** ——其值会随场景或预制件一起保存。如果在 Inspector 中启用后忘记重置，角色在正式构建版本中会悄无声息地忽略所有实时情绪信号。发布前务必将其禁用。
{% endhint %}

## 设置情绪覆盖 / 清除情绪覆盖

`SetEmotionOverride` 会在服务器发送的分数基础上，向累加器注入额外分数。覆盖值仍会经过平滑处理——它会以 `lerpSpeed`的速度逐渐混合，而不是立即生效。当应用逻辑需要根据模拟中的事件增强或引导情绪时，可使用此功能。

```csharp
using Convai.Modules.Emotion.Components;
using UnityEngine;

public sealed class HazardZoneTrigger : MonoBehaviour
{
    [SerializeField] private ConvaiEmotionController emotionController;

    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Trainee"))
            emotionController.SetEmotionOverride("fear", 0.9f);
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.CompareTag("Trainee"))
            emotionController.ClearEmotionOverride();
    }
}
```

`ClearEmotionOverride` 会移除覆盖值，并使累加器恢复为由服务器驱动的状态。恢复过程会经过平滑处理。

## 锁定情绪 / 解锁情绪

`LockEmotion` 会完全绕过累加器，将角色直接切换到指定表情并保持不变，无论服务器发送什么内容。若需要在脚本序列或过场动画期间确保表情稳定不变，可使用此功能。

```csharp
using Convai.Modules.Emotion.Components;
using UnityEngine;

public sealed class WelcomeSequenceController : MonoBehaviour
{
    [SerializeField] private ConvaiEmotionController emotionController;

    public void BeginWelcome()
    {
        emotionController.LockEmotion("joy", 0.75f);
    }

    public void EndWelcome()
    {
        emotionController.UnlockEmotion();
    }
}
```

`UnlockEmotion` 会解除锁定。累加器从中性状态恢复，并重新开始响应服务器事件。

**API 参考：**

```csharp
void LockEmotion(string label, float intensity = 1f);
void UnlockEmotion();
void SetEmotionOverride(string label, float score);
void ClearEmotionOverride();
```

## 在代码中监听情绪变化事件

若要对后端发送的每种新情绪做出响应——用于日志记录、分析或自适应场景逻辑——请订阅 `OnCharacterEmotionChanged` 事件，它位于 `ConvaiManager.Events`中。这是一个标准的 C# 事件，无需管理订阅令牌。

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

public sealed class EmotionEventListener : MonoBehaviour
{
    [SerializeField] private ConvaiManager convaiManager;

    private void OnEnable()
    {
        convaiManager.Events.OnCharacterEmotionChanged += HandleEmotionChanged;
    }

    private void OnDisable()
    {
        convaiManager.Events.OnCharacterEmotionChanged -= HandleEmotionChanged;
    }

    private void HandleEmotionChanged(CharacterEmotionChanged e)
    {
        Debug.Log($"[{e.CharacterId}] {e.Emotion} — intensity {e.Intensity} ({e.NormalizedIntensity:F2})");
    }
}
```

### CharacterEmotionChanged 属性

| 属性                    | 类型         | 说明                                             |
| --------------------- | ---------- | ---------------------------------------------- |
| `CharacterId`         | `string`   | 情绪发生变化的角色的唯一标识符。                               |
| `Emotion`             | `string`   | 服务器返回的原始标签（例如 `"happy"`，而不是 `"joy"`).          |
| `Intensity`           | `int`      | 后端发送的整数等级（1–3，已限制在此范围内）。                       |
| `NormalizedIntensity` | `float`    | `(Intensity - 1) / 2f` — 将 1–3 的范围映射到 \[0, 1]。 |
| `IsNeutral`           | `bool`     | 如果情绪字符串为 `"neutral"`.                          |
| `IsHighIntensity`     | `bool`     | 如果 `Intensity >= 3`.                           |
| `IsLowIntensity`      | `bool`     | 如果 `Intensity <= 1`.                           |
| `Timestamp`           | `DateTime` | 事件创建时的 UTC 时间戳。                                |

{% hint style="warning" %}
`CharacterEmotionChanged.Emotion` 包含 **服务器返回的原始标签** （例如 `"happy"`），而不是规范的分类标签（`"joy"`）。如果需要规范标签（例如，要在 `AllScores` 中查找分数），请通过分类体系进行解析： `taxonomy.TryResolve(e.Emotion, out EmotionDescriptor descriptor)`.
{% endhint %}

## IEmotionStateSource 接口

只需读取情绪状态（无需控制覆盖或锁定）的代码，应依赖 `IEmotionStateSource` 而不是具体的 `ConvaiEmotionController`。这样可以最大限度地减少依赖，也让消费该接口的类更易于独立测试。

```csharp
using Convai.Domain.Embodiment.Interfaces;
using Convai.Domain.Embodiment.Readings;
using UnityEngine;

public sealed class EmotionDrivenUI : MonoBehaviour
{
    // 在 Inspector 中指定一个 ConvaiEmotionController——它实现了 IEmotionStateSource
    [SerializeField] private MonoBehaviour emotionSource;

    private IEmotionStateSource _source;

    private void Awake()
    {
        _source = emotionSource as IEmotionStateSource;
    }

    private void Update()
    {
        EmotionReading reading = _source.Current;
        // 根据 reading.DominantLabel 和 reading.DominantScore 更新 UI
    }
}
```

## 总结

情绪脚本接口涵盖各种集成模式，从无需编写代码的 Unity Events，到完整的强类型 C# 订阅和运行时覆盖。有关将配置文件设置与这些 API 调用结合起来的完整示例，请参阅 [使用示例](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/unity-plugin-beta-overview/features/emotion/usage-examples.md)。如果运行时行为与预期不符，请参阅 [故障排除](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/unity-plugin-beta-overview/features/emotion/troubleshooting-and-diagnostics.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/unity-plugin-beta-overview/features/emotion/scripting-api-reference.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.
