> 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/gaze/scripted-gaze.md).

# 脚本控制的视线

从代码中将 Convai 角色的视线指向某个 Transform 或点，并等待结果，以便在命中后再触发后续动作。

通过代码将角色的视线指向某个变换或世界空间中的某个点，并使用返回的句柄确定注视何时到位。当过场动画的某个情节点、动作执行器或 UI 事件需要控制角色的注视方向，而不使用注视策略已提供的自动目标时，请参阅此页。

### 前提条件

* `ConvaiGazeController` 添加到角色上（`Convai/Embodiment/Gaze`).
* 对角色的 `ConvaiGazeController`的引用，可通过 `GetComponent<ConvaiGazeController>()` 获取，或使用序列化字段。

### 请求脚本控制的注视

调用 `GazeAt` 可发起一个持续请求，直到释放或保持时间结束；调用 `GlanceAt` 则可进行简短的一瞥。两者都会返回一个 `GazeHandle` ，对于有效目标绝不会返回 `null` 。

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

public sealed class DisplayCaseCue : MonoBehaviour
{
    [SerializeField] private Transform displayCase;
    [SerializeField] private ConvaiGazeController gaze;

    private void OnTriggerEnter(Collider other)
    {
        // 保持注视 2 秒；如果展柜不在正前方，则允许角色转动全身。
        gaze.GazeAt(displayCase, new GazeOptions
        {
            HoldSeconds = 2f,
            Engagement = 1f,
            AllowBodyTurn = true
        });
    }
}
```

对于较短、优先级较低的注视，请使用 `GlanceAt` 。它不会转动角色身体，并会自动恢复注视策略指定的目标：

```csharp
gaze.GlanceAt(displayCase, durationSeconds: 1.5f);
```

脚本请求的优先级始终高于自动目标。 `GazeAt` 请求的优先级高于 `GlanceAt` 请求：任何显式的 `GazeAt` 请求都会抢占正在进行的一瞥。

### `GazeOptions` 字段

| 字段              | 类型      | 默认值     | 用途                                                                                                        |
| --------------- | ------- | ------- | --------------------------------------------------------------------------------------------------------- |
| `Priority`      | `int`   | `0`     | 脚本请求之间的优先级（数值越高优先级越高；优先级相同时，较新的请求优先）。                                                                     |
| `HoldSeconds`   | `float` | `0`     | 从发出请求开始计算的保持时长，单位为秒。值为 `<= 0` 时，将持续保持，直到 `GazeHandle.Release()` 被调用。                                      |
| `Engagement`    | `float` | `0`     | 以 `(0, 1]`为单位的参与度覆盖值。值为 `<= 0` 时，使用当前对话状态的参与度——传入一个明确的值（例如 `1`）当无论对话处于何种状态都必须让视线落在目标上时，因为 `Idle` 默认为 `0`. |
| `AllowBodyTurn` | `bool`  | `false` | 此请求是否可以触发角色全身转向目标。                                                                                        |

`GlanceAt` 会自行在内部构建 `GazeOptions` ： `HoldSeconds` 取自其 `durationSeconds` 参数（默认值为 `1.2f`，下限钳制为 `0.2f`), `Engagement` 固定为 `1`，且 `AllowBodyTurn` 固定为 `false`.

### 在 Unity 中等待句柄的

`GazeHandle.Settled` 完成时返回 `true` 表示视线已对准目标；如果请求在对准前结束，则返回 `false` 。 `GazeHandle.Completion` 会在请求结束时完成——无论是保持时间已到、请求已释放，还是目标已丢失。若后续操作依赖角色先明显看向目标（例如做出拾取动作），请先等待 `Settled` 。

```csharp
using System.Threading.Tasks;
using Convai.Modules.Gaze.Components;
using UnityEngine;

public sealed class LookThenReach : MonoBehaviour
{
    public async Task LookAtAndReachAsync(ConvaiGazeController gaze, Transform target)
    {
        GazeHandle handle = gaze.GazeAt(target, new GazeOptions { Engagement = 1f, AllowBodyTurn = true });
        if (handle == null) return;

        bool aligned = await handle.Settled;
        if (!aligned)
        {
            Debug.Log($"Gaze at '{handle.TargetName}' did not settle: {handle.Outcome}.");
            return;
        }

        // 已对准——可以在此处安全地启动伸手或拾取动画。
    }
}
```

{% hint style="warning" %}
`Settled` 可能会以 `false` 完成，这也可能表示请求被有意忽略——见下文的 `GazeOutcome.HeldEyeContactInstead` ——并非只有真正失败时才会如此。在将结果视为错误之前，应根据 `Outcome` 分支判断，而不要只看布尔值。 `false` 。
{% endhint %}

调用 `handle.Release()` 以提前结束请求。 `Release` 可以安全地多次调用，也可以在取消回调中调用。调用 `ConvaiGazeController.ReleaseAllScriptedGaze()` 可一次性结束角色上的所有脚本化请求，例如在过场动画中止时。

### `GazeOutcome` 值

| 值                       | 整数  | 含义                                                                              |
| ----------------------- | --- | ------------------------------------------------------------------------------- |
| `Taken`                 | `0` | 请求仍有效，或视线已到达目标。在有其他结果明确指出之前，这是默认状态。                                             |
| `Interrupted`           | `1` | 视线到达目标前请求已结束——可能是被释放、已过期、被更高优先级的注视取代，或目标已销毁。                                    |
| `HeldEyeContactInstead` | `2` | 角色有意保持眼神接触，并将这次瞥视并入其中，而不是执行瞥视，因为 `LockBlocksGlances` 已启用。没有出错——角色选择了注视对方，而不是物体。 |

### 眼神接触锁定如何影响脚本化请求

`AllowScriptedOverridesDuringExactFocus` 和 `LockBlocksGlances`这两个选项都位于 `ConvaiGazeController`中，用于决定在眼神接触锁定（`ConversationLock` 或 `AlwaysLock` `EyeContactMode`）生效时是否执行脚本化请求：

* 当 `FocusFidelity` 为 `Exact`时，除非 `GazeAt` 请求明确指定 `AllowScriptedOverridesDuringExactFocus` 为 `true`，否则会被直接拒绝。被拒绝的请求会返回一个句柄，其 `Completion` 已完成，且其 `Settled` 解析为 `false`.
* 当 `FocusFidelity` 为 `Social`时，明确发出的 `GazeAt` 请求始终会抢占锁定。
* `GlanceAt` 请求会被吸收，而 `LockBlocksGlances` 为 `true` （默认值）时：返回的句柄会立即完成，结果为 `Outcome` 设为 `HeldEyeContactInstead`，视线也不会离开玩家锚点。将 `LockBlocksGlances` 设为 `false` ，即可让扫视在锁定期间正常播放。

### 故障排查

#### 一个 `GazeAt` 请求始终无法结束

**症状：** `handle.Settled` 等待后返回 `false`.

**原因：** 该请求被优先级更高的脚本请求中断、其目标已被销毁，或者 `Exact` 焦点拒绝了该请求。

**解决方法：** 检查 `handle.Outcome` 在 `Settled` 解析后，以区分 `Interrupted` 和 `HeldEyeContactInstead`，并提高 `Priority` 或设置 `AllowScriptedOverridesDuringExactFocus` （如果该请求应该优先执行）。

**验证：** 后续操作仅在 `Settled` 解析为 `true`.

### 后续步骤

{% content-ref url="/pages/864133eda5776302d8f8f9afeef2de62388e08bc" %}
[视线目标与提供器](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/embodiment/gaze/targets-and-providers.md)
{% endcontent-ref %}

{% content-ref url="/pages/3e45c80fb1153e604c743a1f3a0a835d39719b0e" %}
[配置眼神接触](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/embodiment/gaze/configure-eye-contact.md)
{% endcontent-ref %}

{% content-ref url="/pages/e18fef943d7f4b642c516d5b9e2c689030154ddf" %}
[Gaze 脚本参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/embodiment/gaze/scripting-reference.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/gaze/scripted-gaze.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.
