> 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/embodiment/emotion/usage-examples.md). Agents can also search and read this documentation through its [MCP server](https://docs.convai.com/api-docs/~gitbook/mcp).

# 情绪示例

七个完整场景，涵盖危险情况覆盖、锁定表情、情绪变化、困扰状态分支、分析日志记录，以及无代码 UI 配置。

这些场景展示了 Emotion 系统的配置与脚本 API 如何结合，满足实际应用需求。每个场景均可独立理解：先介绍 Inspector 设置，再给出实现相应行为所需的运行时代码。配置文件字段的说明见 [Emotion 配置文件](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/embodiment/emotion/emotion-profile.md)；完整的脚本 API 见 [Emotion 脚本 API](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/embodiment/emotion/scripting-api.md).

### 场景 1：动态应对危险

**情境：** 一名讲师 NPC 引导学员进行消防疏散模拟。当学员进入标记的危险区域时，讲师的表情应迅速转为恐惧或紧迫，以强调情况的严重性。学员离开该区域后，表情则恢复为由服务器驱动的状态。

#### 配置文件设置

打开分配给讲师 NPC 的 `ConvaiEmotionProfile` 并调整以下参数：

* **`lerpSpeed`** → `12` — 快速上升，使恐惧表情立即呈现。
* **`microBurstOvershoot`** → `1.6` — 明显的突发效果能让转变更具视觉冲击力。
* **`microBurstDuration`** → `0.2 s` — 短暂突发后，表情逐渐稳定。

#### 运行时脚本

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

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

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

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

`SetEmotionOverride` 会在 Convai 当前发送的情绪分值上叠加恐惧分值。累加器会按照已配置的 `lerpSpeed`将其混合进来，因此覆盖效果既迅速又自然。 `ClearEmotionOverride` 在触发器退出时调用，可让服务器信号恢复完全控制。无需为面部表情的各个槽位单独创作——表情配方会自动根据角色骨架解析 `"fear"` 。

***

### 场景 2：锁定欢迎表情

**情境：** 一名迎宾 NPC 站在入门模拟场景的入口处。在欢迎流程中——也就是学员尚未开始说话之前——无论 Convai 在连接握手期间发送何种情绪信号，角色都应始终显得亲切友好、平易近人。

#### 运行时脚本

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

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

    private void Start()
    {
        // 从第一帧开始保持温和、亲切的表情
        greeterEmotion.LockEmotion("joy", 0.65f);
    }

    public void OnWelcomeSequenceComplete()
    {
        // 解除锁定，让角色对对话做出自然反应
        greeterEmotion.UnlockEmotion();
    }
}
```

锁定的情绪强度为 `0.65` 时，会呈现明显但不过分夸张的微笑，适合专业场合。 `UnlockEmotion` 在模拟切换到开放式对话时调用，此时角色开始响应实时 AI 信号。

***

### 场景 3：在一场会话中逐渐变得更热情的角色

**情境：** 客服培训师 NPC 应在每场会话开始时保持中性、专业的静息情绪，并随着学员妥善应对对话而明显变得更热情——这种静息情绪的变化是培训师之后可以指出的，与对话期间的瞬时反应有所区别。

#### 运行时脚本

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

public sealed class RapportDirector : MonoBehaviour
{
    [SerializeField] private ConvaiEmotionController trainerEmotion;
    [SerializeField] private int goodExchangeCount;
    private const int WarmupThreshold = 3;

    public void OnExchangeScoredWell()
    {
        goodExchangeCount++;
        if (goodExchangeCount == WarmupThreshold)
            trainerEmotion.SetMood("joy", 0.5f, transitionSeconds: 4f);
    }

    public void OnSessionReset()
    {
        goodExchangeCount = 0;
        trainerEmotion.ClearMood();
    }
}
```

`SetMood` 会改变角色的 **静息情绪** ——即面部在瞬时反应之间恢复到的情绪——而不是注入一次性的表情。四秒的过渡会呈现出逐渐变得热情的效果，而非情绪突然转变。 `ClearMood` 会在会话重置时将角色恢复到设定的基线状态。有关静息情绪与瞬时情绪的区别，请参阅 [情绪状态](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/embodiment/emotion/moods.md) ；有关完整的优先级规则，请参阅 [情绪脚本 API](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/embodiment/emotion/scripting-api.md#runtime-mood-control) 。

***

### 场景 4：基于情绪状态的分支逻辑

**情境：** 在医疗沟通评估中，如果虚拟病人 NPC 认为学员的回应带有敷衍意味，就会变得痛苦。导演脚本会监控 NPC 的情绪状态；如果检测到持续的痛苦情绪，就将场景切换到缓和情绪的分支。

#### 运行时脚本

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

public sealed class EmotionBranchDirector : MonoBehaviour
{
    [SerializeField] private ConvaiEmotionController patientEmotion;
    [SerializeField] private float distressThreshold = 0.6f;
    [SerializeField] private float sustainedDistressSeconds = 4f;
    [SerializeField] private UnityEvent onDistressBranchTriggered;

    private bool _branchTriggered;

    private void Update()
    {
        if (_branchTriggered) return;

        EmotionReading reading = patientEmotion.Current;

        bool isSadOrFearful = reading.DominantLabel is "sadness" or "fear"
                              && reading.DominantScore >= distressThreshold;

        if (isSadOrFearful && reading.DominantHoldSeconds >= sustainedDistressSeconds)
        {
            _branchTriggered = true;
            onDistressBranchTriggered.Invoke();
        }
    }
}
```

`DominantHoldSeconds` 用于记录当前主导情绪持续保持的时间。将它与分数阈值配合使用，可以防止短暂的情绪峰值触发分支——只有痛苦情绪确实持续一段时间，场景才会推进。

***

### 场景 5：会话分析日志记录

**情境：** 某培训平台需要记录 AI 角色在会话期间经历的每一次情绪变化，包括原始服务器标签和强度，以便讲师在会话结束后的报告中回顾对话中的情绪变化过程。

#### 运行时脚本

```csharp
using Convai.Domain.DomainEvents.Runtime;
using Convai.Runtime.Components;
using System.Collections.Generic;
using UnityEngine;

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

    private readonly List<string> _emotionLog = new();

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

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

    private void HandleEmotionChanged(CharacterEmotionChanged e)
    {
        string entry = $"[{e.Timestamp:HH:mm:ss.fff}] {e.CharacterId}: {e.Emotion} (scale {e.Intensity})";
        _emotionLog.Add(entry);
        Debug.Log(entry);
    }

    public IReadOnlyList<string> GetLog() => _emotionLog;
}
```

`OnCharacterEmotionChanged` 会在 Convai 发出每个情绪信号时触发，此时控制器尚未对其进行平滑处理或加工。这让分析代码能够获取原始信号，而非插值后的视觉状态，更有利于回顾会话。若要记录角色最终实际表达的情绪，请改为订阅 `DominantEmotionChanged`/`MoodChanged` ——请参阅 [情绪脚本 API](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/embodiment/emotion/scripting-api.md#resolved-emotion-and-mood-events).

***

### 场景 6：无代码 UI 显示

**情境：** 非程序员希望在角色当前情绪发生变化时更新显示该情绪的 UI 标签，而且不编写任何代码。

{% stepper %}
{% step %}

#### 添加事件中继

选择 NPC 的根 GameObject。点击 **添加组件** 并导航至 **Convai → Events → Convai Character Event Relay**.

该中继会通过默认启用的 `ConvaiCharacter` 同一 GameObject 上的 **自动解析角色** 开关自动解析角色。
{% endstep %}

{% step %}

#### 连接 On Emotion Changed 事件

在 **On Emotion Changed** Unity Event 列表中，找到 `ConvaiCharacterEventRelay`，点击 **+**.
{% endstep %}

{% step %}

#### 指定 UI Text 组件

将 UI `Text` （或 `TMP_Text`）组件拖到新事件条目的对象字段中。
{% endstep %}

{% step %}

#### 选择目标属性

在函数下拉菜单中，选择 **Text → string text** （或 **TMP\_Text → string text**).

此后，每当角色的情绪发生变化， `Emotion` 属性就会从 `CharacterEmotionRelayData` 直接写入标签中——无需编写代码。
{% endstep %}
{% endstepper %}

{% hint style="success" %}
进入播放模式并与角色交谈。随着 Convai 发送新的情绪信号，UI 标签会自动更新。
{% endhint %}

`ConvaiCharacterEventRelay` 会传递服务器返回的原始标签（例如 `"happy"`）。如果需要更友好的显示名称（例如 `"Joy"` 而不是 `"happy"`），可以添加一个小型格式化脚本，将原始标签映射为显示字符串；也可以在 UnityEvent 目标方法中对字符串进行后处理。

***

### 场景 7：在编辑器中预览表情

**情境：** 你已配置好角色的骨架，想在进入播放模式前确认每种情绪都能驱动出易于辨认的表情。

1. 选择 NPC 的根 GameObject。
2. 在 `ConvaiEmotionController` 组件上，启用 **锁定情绪**.
3. 将 **锁定的情绪标签** 设为要预览的规范标签（例如 `"anger"`).
4. 将 **锁定强度** 设为 `1.0`.

场景视图会立即更新——由于 `ConvaiEmotionController` 继承了其基类的 `[ExecuteAlways]` ，因此表情方案会在编辑模式下解析并应用。轮流选择情绪分类中的标签，以直观验证每种表情；也可以使用 [情绪编辑器窗口](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/embodiment/emotion/emotion-editor.md) ，逐一预览已打开场景中的所有角色。

{% hint style="danger" %}
在生产构建前，将 **锁定情绪** 重新设为 `false` 。该字段会被序列化——如果仍处于启用状态，角色在发布版本中将忽略所有后端情绪信号，且不会产生运行时错误或警告。
{% endhint %}

### 后续步骤

有关上述配置文件设置中使用的完整参数参考，请参阅 [情绪配置文件](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/embodiment/emotion/emotion-profile.md)。有关完整的脚本接口，请参阅 [情绪脚本 API](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/embodiment/emotion/scripting-api.md)。如果任何场景未产生预期结果，请参阅 [情绪问题排查](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/embodiment/emotion/troubleshooting-and-diagnostics.md).

{% content-ref url="/pages/5a9247365092d958f2d539ae98bdfe69f72df091" %}
[Emotion 配置文件](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/embodiment/emotion/emotion-profile.md)
{% endcontent-ref %}

{% content-ref url="/pages/39d161d99d04e6ca98725c740d134ccb5eac9e73" %}
[Emotion 脚本 API](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/embodiment/emotion/scripting-api.md)
{% endcontent-ref %}

{% content-ref url="/pages/65ec9decd2473b72bc06bf3c946f3008c8528dda" %}
[排查情绪问题](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/embodiment/emotion/troubleshooting-and-diagnostics.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/embodiment/emotion/usage-examples.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.
