> 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/gaze-and-attention/scripting-api.md).

# 注视与注意力脚本 API

Gaze & Attention 系统公开两个独立的 API 接口： **注意力系统** （角色看向什么）以及 **注视系统** （它如何看起来）。除注明外，二者在运行时均为只读。

***

### 注意力系统

#### ConvaiAttentionController

**命名空间：** `Convai.Modules.Attention.Components`\
**组件菜单：** Convai → Embodiment → Attention Controller

| 成员                   | 类型                       | 描述                                                  |
| -------------------- | ------------------------ | --------------------------------------------------- |
| `当前`                 | `AttentionReading` （get） | 当前注意力快照。每帧更新。可安全地从 `Update()`.                      |
| `RefreshProviders()` | `void`                   | 重新扫描角色层级中的 `IFocusTargetProvider` 组件。请在运行时添加提供者后调用。 |

***

#### AttentionReading

**命名空间：** `Convai.Domain.Embodiment.Readings`\
**类型：** `readonly struct`

角色当前关注对象的不可变快照。由 `ConvaiAttentionController.Current`.

| 属性                   | 类型                          | 描述                                                               |
| -------------------- | --------------------------- | ---------------------------------------------------------------- |
| `IsValid`            | `bool`                      | `true` 当该读数表示一个可用的注意力目标时。 `false` 在空闲状态下或当没有提供者返回候选项时。           |
| `Target`             | `Transform`                 | 被关注的 Transform。对于仅由世界空间点定义的候选项，可能为 `null` 。                      |
| `SmoothedPoint`      | `Vector3`                   | 平滑后的世界空间焦点。将其用于注视目标定位——它能避免目标在帧与帧之间移动造成的抖动。                      |
| `Commitment`         | `float`                     | \[0, 1] 范围内的归一化承诺度。1 = 完全投入；0 = 脱离。会根据 `ConvaiAttentionProfile`. |
| `TargetGenerationId` | `int`                       | 稳定的整数，每当注意力转移到新目标时递增一次。跨帧比较即可检测注意力切换，而无需轮询标识。 `Target` 标识。       |
| `Empty`              | `AttentionReading` （static） | 预构建的脱离状态读数（`IsValid = false`, `Commitment = 0`).                 |

**检测注意力切换：**

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

public class AttentionSwitchDetector : MonoBehaviour
{
    [SerializeField] private ConvaiAttentionController _attention;

    private int _lastGenerationId;

    private void Update()
    {
        var reading = _attention.Current;

        if (reading.TargetGenerationId != _lastGenerationId)
        {
            _lastGenerationId = reading.TargetGenerationId;
            OnAttentionSwitched(reading);
        }
    }

    private void OnAttentionSwitched(AttentionReading reading)
    {
        if (!reading.IsValid)
            Debug.Log("注意力已释放——角色处于空闲状态。");
        else
            Debug.Log($"现在关注：{reading.Target?.name ?? \"world point\"} " +
                      $"位于 {reading.SmoothedPoint}");
    }
}
```

***

#### AttentionCandidate

**命名空间：** `Convai.Domain.Embodiment.Readings`\
**类型：** `readonly struct`

由 `IFocusTargetProvider.TryGetCandidate()` 每帧产生。注意力控制器会评估所有候选项并选出胜者。

| 属性           | 类型          | 描述                                             |
| ------------ | ----------- | ---------------------------------------------- |
| `优先级`        | `int`       | 用于平局裁决的静态排序提示。当相关性分数相同时，优先级更高的候选项获胜。           |
| `相关性`        | `float`     | \[0, 1] 范围内的当前相关性。驱动选择概率。 `0` = 对注意力系统而言几乎不可见。 |
| `Target`     | `Transform` | 支撑此候选项的可选 Transform。可能为 `null`.                |
| `WorldPoint` | `Vector3`   | 要看的世界空间点。当 `Target` 为 `null`.                  |
| `DebugName`  | `string`    | 在诊断日志中显示的简短标识符。                                |

***

#### IFocusTargetProvider

**命名空间：** `Convai.Domain.Embodiment.Interfaces`

在任何 `MonoBehaviour` 上实现此接口，以提供注意力候选项。位于角色 GameObject 或其子对象上的实现了此接口的组件，会在 **Discover Providers In Hierarchy** 启用时自动发现。

| 成员                                              | 类型          | 描述                                                          |
| ----------------------------------------------- | ----------- | ----------------------------------------------------------- |
| `优先级`                                           | `int` （get） | 跨提供者用于平局裁决的静态优先级。默认摄像机提供者使用的优先级 `0`.                        |
| `TryGetCandidate(characterRoot, out candidate)` | `bool`      | 每帧调用。返回 `true` 并填充 `candidate` 以提议一个目标。返回 `false` 以在本帧退出竞争。 |

**最小实现：**

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

public class ObjectOfInterestProvider : MonoBehaviour, IFocusTargetProvider
{
    [SerializeField] private Transform _target;
    [SerializeField] private float _relevance = 0.75f;

    public int Priority => 5;

    public bool TryGetCandidate(Transform characterRoot, out AttentionCandidate candidate)
    {
        if (_target == null)
        {
            candidate = default;
            return false;
        }

        candidate = new AttentionCandidate(
            priority: Priority,
            relevance: _relevance,
            target: _target,
            worldPoint: _target.position,
            debugName: "ObjectOfInterest"
        );
        return true;
    }
}
```

***

### 注视系统

#### ConvaiGazeCoordinator

**命名空间：** `Convai.Modules.Gaze.Components`\
**组件菜单：** Convai → Embodiment → Gaze Coordinator

{% hint style="warning" %}
`ConvaiGazeCoordinator` 由 `ConvaiEyeGazeActuator` 在初始化期间自动创建。不要从 `Awake()` 中访问它——它此时尚不存在。请使用 `Start()` 或更后面的生命周期事件。
{% endhint %}

| 成员   | 类型                 | 描述                                                |
| ---- | ------------------ | ------------------------------------------------- |
| `当前` | `GazeIntent` （get） | 本帧计算出的当前注视意图。在 `ConvaiAttentionController` 运行后更新。 |

***

#### GazeIntent

**命名空间：** `Convai.Domain.Embodiment.Readings`\
**类型：** `readonly struct`

……的输出 `ConvaiGazeCoordinator`。由 `ConvaiEyeGazeActuator` 和 `ConvaiHeadLookActuator`.

| 属性                 | 类型                    | 描述                                                |
| ------------------ | --------------------- | ------------------------------------------------- |
| `WorldTargetPoint` | `Vector3`             | 眼部和头部执行器应朝向的世界空间点                                 |
| `OverallWeight`    | `float`               | \[0, 1] 范围内的整体注视权重。缩放执行器跟踪目标的强度。                  |
| `EyeShare`         | `float`               | 仅由眼睛单独处理的跟踪比例。头部处理 `1 − EyeShare`.                |
| `Relaxed`          | `GazeIntent` （static） | 预构建的脱离状态意图（`OverallWeight = 0`）。当协调器没有有效注意力输入时使用。 |

***

#### ConvaiHeadLookActuator

**命名空间：** `Convai.Modules.Gaze.Components`\
**组件菜单：** Convai → Embodiment → Head Look

| 成员                     | 类型              | 描述                                            |
| ---------------------- | --------------- | --------------------------------------------- |
| `CurrentHeadAuthority` | `float` （get）   | 当前头部旋转权威级别（已平滑，考虑到 `MinimumHeadContribution`) |
| `IsIdleExploring`      | `bool` （get）    | `true` 当头部执行器正在运行其空闲探索行为时（空闲对话状态下会抑制注意力）      |
| `CurrentSolvedAngles`  | `Vector2` （get） | 当前应用到颈部/头部链的已求解偏航（x）和俯仰（y）角度，单位为度             |

***

#### ConvaiEyeGazeActuator

**命名空间：** `Convai.Modules.Gaze.Components`\
**组件菜单：** Convai → Embodiment → Eye Gaze

除标准 Unity 组件成员外，眼部执行器没有可在运行时读取的状态属性。使用 `ConvaiGazeCoordinator.Current` 来读取注视意图，以及 `ConvaiAttentionController.Current` 来读取注意力状态。

***

### 脚本示例

#### 为 UI 指示器读取承诺度

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

public class CommitmentBar : MonoBehaviour
{
    [SerializeField] private ConvaiAttentionController _attention;
    [SerializeField] private Slider _slider;

    private void Update()
    {
        _slider.value = _attention.Current.Commitment;
    }
}
```

***

#### 在场景加载后注册运行时提供者

如果你在运行时添加一个 `IFocusTargetProvider` 组件（例如实例化一个道具），请调用 `RefreshProviders()` 这样注意力控制器就会识别它：

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

public class RuntimePropSpawner : MonoBehaviour
{
    [SerializeField] private ConvaiAttentionController _attention;
    [SerializeField] private GameObject _propPrefab;

    public void SpawnProp(Vector3 position)
    {
        var prop = Instantiate(_propPrefab, position, Quaternion.identity);

        // 提供者在新道具上——刷新以便控制器看到它
        _attention.RefreshProviders();
    }
}
```

***

#### 区分注意力与注视诊断

使用 `AttentionReading.IsValid` 在注视看起来不对时，判断应排查哪个系统：

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

public class GazeDiagnostics : MonoBehaviour
{
    [SerializeField] private ConvaiAttentionController _attention;

    private void Update()
    {
        if (!_attention.Current.IsValid)
        {
            // 问题出在注意力系统：
            // 没有提供者返回候选项，或所有相关性分数都为 0
            Debug.Log("注意力：没有有效目标");
        }
        else
        {
            // 注意力有效——如果眼睛/头部仍然静止，
            // 问题出在注视系统（配置文件、骨骼配置或协调器）
            Debug.Log($"注意力有效。目标：{_attention.Current.Target?.name}, " +
                      $"承诺度：{_attention.Current.Commitment:F2}");
        }
    }
}
```

***

### 下一步

如需帮助处理常见故障——眼睛静止、头部冻结或缺少注意力目标——请参阅故障排除页面。

{% content-ref url="/pages/bd1a14b7112ed8774594e9ba50650f3d5c339af2" %}
[注视与注意力故障排除](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/utilities/gaze-and-attention/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/gaze-and-attention/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.
