> 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/utilities/dialogue-animation/scripting-api.md).

# 对话动画脚本 API

`ConvaiDialogueAnimationController` 暴露一个只读状态接口和两个运行时切换方法。所有属性都可以安全地在每一帧从任何脚本中查询。

***

### ConvaiDialogueAnimationController

**命名空间：** `Convai.Modules.DialogueAnimation.Components`\
**组件菜单：** Convai → Embodiment → Dialogue Animation

#### 方法

| 方法                    | Parameters                              | 说明                                  |
| --------------------- | --------------------------------------- | ----------------------------------- |
| `SetLibrary(library)` | `DialogueAnimationLibrary library`      | 立即切换当前活动的片段池。将在下一次片段选择周期生效。         |
| `SetConfig(config)`   | `DialogueAnimationRuntimeConfig config` | 替换当前活动的运行时配置。时间和权重的更改将在下一次 tick 生效。 |

#### 已分配资源属性

| 属性                | 类型                               | 说明                                  |
| ----------------- | -------------------------------- | ----------------------------------- |
| `库`               | `DialogueAnimationLibrary`       | 当前分配的库                              |
| `配置`              | `DialogueAnimationRuntimeConfig` | 当前分配的配置                             |
| `Contract`        | `DialogueAnimatorContract`       | 当前活动的 Animator 契约（如果使用默认值，可能为 null） |
| `CharacterGender` | `CharacterGender`                | 用于片段选择的当前性别筛选器                      |

#### 验证

| 属性                    | 类型     | 说明                                               |
| --------------------- | ------ | ------------------------------------------------ |
| `HasValidIdleLibrary` | `bool` | `true` 当分配的库至少有一个有效的 idle 片段时为真。请在启动时使用它来捕获配置错误。 |

#### 当前片段属性

| 属性                          | 类型              | 说明                      |
| --------------------------- | --------------- | ----------------------- |
| `CurrentFoundationIdleClip` | `AnimationClip` | 当前分配到 Base Idle 槽位的片段   |
| `CurrentIdleOverlayClip`    | `AnimationClip` | 当前在 Idle Overlay 层播放的片段 |
| `CurrentBodyTalkClip`       | `AnimationClip` | 当前在 Body Talk 层播放的片段    |
| `CurrentTalkClip`           | `AnimationClip` | 当前在 Head Talk 层播放的片段    |

#### 层权重属性

| 属性                              | 类型      | 说明                                                                                                          |
| ------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------- |
| `CurrentBaseIdleLayerWeight`    | `float` | Base Idle 层（Layer 0）的当前权重                                                                                   |
| `CurrentIdleOverlayLayerWeight` | `float` | Idle Overlay 层（Layer 1）的当前权重                                                                                |
| `CurrentBodyTalkLayerWeight`    | `float` | Body Talk 层（Layer 2）的当前权重                                                                                   |
| `CurrentHeadTalkLayerWeight`    | `float` | Head Talk 层（Layer 3）的当前权重                                                                                   |
| `CurrentTalkLayerWeight`        | `float` | 当前最强的活动对话层贡献—— `max(CurrentBodyTalkLayerWeight, CurrentHeadTalkLayerWeight)`。可将其用于驱动需要单一“正在说话”信号的 UI 或外部系统。 |

#### 运行时层索引属性

| 属性                             | 类型    | 说明                                 |
| ------------------------------ | ----- | ---------------------------------- |
| `RuntimeBaseIdleLayerIndex`    | `int` | 运行时解析得到的 Base Idle Animator 层索引    |
| `RuntimeIdleOverlayLayerIndex` | `int` | 运行时解析得到的 Idle Overlay Animator 层索引 |
| `RuntimeBodyTalkLayerIndex`    | `int` | 运行时解析得到的 Body Talk Animator 层索引    |
| `RuntimeHeadTalkLayerIndex`    | `int` | 运行时解析得到的 Head Talk Animator 层索引    |

#### 选择诊断属性

| 属性              | 类型    | 说明                                     |
| --------------- | ----- | -------------------------------------- |
| `LastIdleIndex` | `int` | 在库的 `IdleEntries` 用于最近一次选中的 idle 片段的数组 |
| `LastTalkIndex` | `int` | 在库的 `TalkEntries` 用于最近一次选中的 talk 片段的数组 |

***

### 脚本示例

#### 在启动时验证配置

检查 `HasValidIdleLibrary` 在会话开始前，以便尽早捕获缺失的库分配：

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

public class AnimationValidator : MonoBehaviour
{
    [SerializeField] private ConvaiDialogueAnimationController _animController;

    private void Start()
    {
        if (!_animController.HasValidIdleLibrary)
        {
            Debug.LogError(
                $"[{name}] 分配的库中没有有效的 idle 片段。 " +
                "请分配一个至少包含一个 idle 条目的 DialogueAnimationLibrary。",
                this);
        }
    }
}
```

***

#### 根据对话层权重驱动 UI 参与度指示器

`CurrentTalkLayerWeight` 从 Animator 的内部缓存中每帧更新：

```csharp
using Convai.Modules.DialogueAnimation.Components;
using UnityEngine;
using UnityEngine.UI;

public class TalkLayerIndicator : MonoBehaviour
{
    [SerializeField] private ConvaiDialogueAnimationController _animController;
    [SerializeField] private Slider _engagementSlider;

    private void Update()
    {
        _engagementSlider.value = _animController.CurrentTalkLayerWeight;
    }
}
```

***

#### 根据模拟事件切换库

```csharp
using Convai.Modules.DialogueAnimation.Components;
using Convai.Modules.DialogueAnimation.Core;
using UnityEngine;

public class ContextualAnimationSwap : MonoBehaviour
{
    [SerializeField] private ConvaiDialogueAnimationController _animController;
    [SerializeField] private DialogueAnimationLibrary _calmLibrary;
    [SerializeField] private DialogueAnimationLibrary _urgentLibrary;

    public void OnEmergencyAlert()
    {
        _animController.SetLibrary(_urgentLibrary);
    }

    public void OnStandDown()
    {
        _animController.SetLibrary(_calmLibrary);
    }
}
```

***

#### 使用单独的配置资源，以实现多角色独立片段选择

为防止两个角色同步选择相同的片段，请创建独立的 `DialogueAnimationRuntimeConfig` 资源，并设置不同的 `DeterministicSeed` 在 Inspector 中为每个资源设置不同的值。然后在运行时分配每个配置：

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

public class MultiCharacterSetup : MonoBehaviour
{
    [SerializeField] private ConvaiDialogueAnimationController[] _characters;
    // 在 Inspector 中为每个角色分配一个配置资源。
    // 在每个配置资源上设置不同的 DeterministicSeed，以使其 RNG 流不同。
    [SerializeField] private DialogueAnimationRuntimeConfig[] _perCharacterConfigs;

    private void Awake()
    {
        for (int i = 0; i < _characters.Length; i++)
        {
            _characters[i].SetConfig(_perCharacterConfigs[i]);
        }
    }
}
```

***

#### 监控层权重，用于参与度仪表板

同时读取四个层权重，以驱动按层可视化：

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

public class LayerWeightDashboard : MonoBehaviour
{
    [SerializeField] private ConvaiDialogueAnimationController _ctrl;

    private void Update()
    {
        float idle     = _ctrl.CurrentBaseIdleLayerWeight;
        float overlay  = _ctrl.CurrentIdleOverlayLayerWeight;
        float bodyTalk = _ctrl.CurrentBodyTalkLayerWeight;
        float headTalk = _ctrl.CurrentHeadTalkLayerWeight;

        // 这四个值都直接读取 Animator 的实时缓存——不产生堆分配
        Debug.Log($"Idle:{idle:F2} Overlay:{overlay:F2} Body:{bodyTalk:F2} Head:{headTalk:F2}");
    }
}
```

***

### 下一步

有关运行时诊断动画问题的帮助，请参阅故障排除页面。

{% content-ref url="/pages/0701ede6b3c4cdf57154ba57ba35ff6bd82a86bf" %}
[对话动画故障排除](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/utilities/dialogue-animation/troubleshooting.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 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/convai-unity-sdk/utilities/dialogue-animation/scripting-api.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.
