> 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/usage-examples.md).

# 使用示例

## 实践中的情绪：示例场景

下面的示例展示了 Emotion 系统的配置与脚本 API 如何结合起来满足真实的应用需求。每个场景都是独立的：先描述 Inspector 设置，然后给出完成该行为所需的任何运行时代码。配置文件和绑定字段的参考见 Emotion Profile 和 Output Bindings；完整的脚本接口见 Scripting API。

## 场景 1 — 安全培训：动态危险响应

**情境：** 一名讲师 NPC 引导受训者完成火灾疏散模拟。当受训者进入标记的危险区域时，讲师的表情应迅速转为恐惧或紧迫，以强化情境的严重性。当受训者离开该区域时，表情恢复为服务器驱动的状态。

### 配置文件设置

打开 `ConvaiEmotionProfile` 分配给讲师 NPC 并调整：

* **`lerpSpeed`** → `12` — 快速上升，使恐惧表情不延迟地出现。
* **`microBurstOvershoot`** → `1.6` — 明显的爆发使过渡在视觉上更有冲击力。
* **`microBurstDuration`** → `0.2 秒` — 表情稳定前的短暂爆发。

### 输出绑定

添加一个插槽到 **Blendshape Binding**:

<table><thead><tr><th>emotionLabel</th><th>blendshapeNames</th><th width="156">weightMultiplier</th><th>fullBlendshapeWeight</th></tr></thead><tbody><tr><td><code>fear</code></td><td><code>Brow_Raise_Inner_L, Brow_Raise_Inner_R, Eye_Wide_L, Eye_Wide_R</code></td><td><code>1.0</code></td><td><code>85</code></td></tr></tbody></table>

### 运行时脚本

```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` 会在服务器当前发送的任何内容之上叠加恐惧分数。累加器会在配置的 `lerpSpeed`处将其融合，因此覆盖会快速但自然地到达。 `ClearEmotionOverride` 在触发器退出时调用，让服务器可以重新获得完全控制权。

***

## 场景 2 — 员工入职：锁定欢迎表情

**情境：** 一名迎宾 NPC 站在入职模拟的入口处。在欢迎流程期间——也就是受训者开始说话之前——无论连接握手期间后端可能发送什么情绪信号，这个角色都应始终显得热情且平易近人。

### 运行时脚本

```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，在受训者的回答被视为轻慢时会变得不安。导演脚本会监视该 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` 用于跟踪当前主导情绪被持续保持了多久。将它与分数阈值一起使用，可避免短暂峰值触发分支——只有真正持续的不安才会推动场景前进。

***

## 场景 4 — 会话分析：记录情绪弧线

**情境：** 一个培训平台需要记录 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` 会在来自后端的每一个情绪信号上触发，且发生在控制器对其进行平滑处理之前。这让分析代码可以访问原始信号，而不是插值后的视觉状态，这对会话回顾更有意义。

***

## 场景 5 — 无代码 UI：由 Inspector 驱动的情绪显示

**情境：** 一位不会编程的人希望在角色当前情绪变化时更新显示该情绪的 UI 标签，而无需编写任何代码。

### 设置

1. 添加 `ConvaiCharacterEventRelay` 到 NPC 根 GameObject（**Convai → Events → Convai Character Event Relay**）。它会自动解析同一对象上的 `ConvaiCharacter` 。
2. 在 **On Emotion Changed** Unity Event 列表中，点击 **+**.
3. 将你的 UI `Text` （或 `TMP_Text`）组件拖到对象字段中。
4. 从函数下拉菜单中选择 **Text → string text** （或 **TMP\_Text → string text**).

现在，每当角色的情绪发生变化时，来自 `Emotion` 属性的 `CharacterEmotionRelayData` 会直接写入标签——无需代码。

{% hint style="info" %}
`ConvaiCharacterEventRelay` 会传递原始服务器标签（例如 `"happy"`）。如果你需要更友好的显示名称（例如 `"Joy"` 而不是 `"happy"`），添加一个小型格式化脚本，将原始标签映射为显示字符串，或者在 UnityEvent 目标方法中对字符串进行后处理。
{% endhint %}

***

## 场景 6 — 内容创作：在编辑器中预览表情

**情境：** 你已经为一个新角色添加了 blendshape 插槽，并希望在进入 Play Mode 之前确认每种情绪是否将正确的形状驱动到正确的权重。

### 步骤

1. 选择 NPC 的根 GameObject。
2. 在 `ConvaiEmotionController` 组件上，启用 **Lock Emotion**.
3. 将 **Locked Emotion Label** 设置为你想要预览的规范标签（例如 `"anger"`).
4. 将 **Locked Intensity** 设为 `1.0`.

Scene 视图会立即更新——blendshape 会在 Edit Mode 中应用，因为 `ConvaiEmotionController` 是 `[ExecuteAlways]`。在你的分类体系中切换这些标签，以可视化方式验证每个插槽的映射。

{% hint style="danger" %}
将 **Lock Emotion** 改回 `false` ，然后再发布构建。该字段是序列化保存的——如果它保持启用，角色在生产环境中将忽略所有后端情绪信号。
{% endhint %}

## 结论

这六个场景涵盖了最常见的情绪集成模式——从危险触发器和脚本锁定，到无代码 Unity Event 连接和编辑器创作工作流。关于上面配置设置所用参数的完整参考，请参见 [Emotion Profile](/api-docs/zh/cha-jian-yu-ji-cheng/unity-plugin-beta-overview/features/emotion/emotion-profile.md)。关于完整的脚本接口，请参见 [Scripting API](/api-docs/zh/cha-jian-yu-ji-cheng/unity-plugin-beta-overview/features/emotion/scripting-api-reference.md)。如果任何场景没有产生预期结果，请参见 [故障排除](/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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/unity-plugin-beta-overview/features/emotion/usage-examples.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
