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

# 视觉使用示例

查找常见视觉设置的代码模式，包括安全培训、摄像头选择、注视激活、按需触发和 WebGL 部署。

这些示例涵盖了最常见的 Vision 集成模式。每个示例都是独立的——复制相关脚本，将其附加到相应的 GameObject，并在 Inspector 中配置序列化字段。

### 在安全培训中监控物体摆放

一个安全培训应用：Convai 角色会监控用户是否将设备放置在正确区域，并以语音提供反馈。角色使用实时场景摄像头画面，观察物体摆放情况。

**预期效果：** 当玩家移动物体时，角色会描述其位置，并确认摆放是否正确，或指出安全问题。

```csharp
using Convai.Modules.Vision;
using Convai.Runtime.Vision.Publishing;
using UnityEngine;

/// <summary>
/// 在培训序列开始时启用视觉功能，并在完成时将其禁用。
/// 附加到与 ConvaiVisionPublisher 相同的 GameObject。
/// </summary>
public class SafetyTrainingVisionController : MonoBehaviour
{
    [SerializeField] private ConvaiVisionPublisher _publisher;

    void Awake()
    {
        // 从 Manual 模式开始，这样只有在培训进行期间才会采集视觉画面
        _publisher.SetPublishPolicy(VisionPublishPolicy.Manual);
    }

    public void BeginTrainingSequence()
    {
        _publisher.SetPublishPolicy(VisionPublishPolicy.HighResponsiveness);
        _publisher.EnablePublishing(true);
    }

    public void EndTrainingSequence()
    {
        _publisher.EnablePublishing(false);
        _publisher.SetPublishPolicy(VisionPublishPolicy.Manual);
    }
}
```

### 在运行时选择摄像头设备

一个桌面端引导应用，用户可在会话开始前选择要使用的实体摄像头。当用户的工作站配备多个摄像头（内置摄像头、USB 摄像头等）时，此功能非常实用。

**预期效果：** 启动时，下拉列表会填充所有检测到的摄像头名称。选择摄像头名称并点击 **切换** 即可更换采集设备，而无需停止会话。

```csharp
using System.Collections.Generic;
using Convai.Runtime.Vision.Sources;
using TMPro;
using UnityEngine;

/// <summary>
/// 使用可用的摄像头名称填充 TMP_Dropdown，并按需切换设备。
/// 场景中需要有 WebcamVisionFrameSource。
/// </summary>
public class WebcamSelectorUI : MonoBehaviour
{
    [SerializeField] private WebcamVisionFrameSource _webcamSource;
    [SerializeField] private TMP_Dropdown _deviceDropdown;

    private List<string> _deviceNames = new();

    async void Start()
    {
        _deviceNames = new List<string>(WebcamVisionFrameSource.GetAvailableDeviceNames());
        _deviceDropdown.ClearOptions();
        _deviceDropdown.AddOptions(_deviceNames);

        _deviceDropdown.onValueChanged.AddListener(async index =>
        {
            if (index >= 0 && index < _deviceNames.Count)
                await _webcamSource.SwitchWebcamAsync(_deviceNames[index]);
        });
    }
}
```

{% hint style="info" %}
`TMP_Dropdown` 需要 TextMeshPro 包。如果你的项目使用旧版 `UnityEngine.UI.Dropdown`，请将 `TMP_Dropdown` 替换为 `Dropdown` —— `AddOptions(List<string>)` 的工作方式完全相同。
{% endhint %}

### 串流高处的安防摄像头画面

一个建筑漫游场景，其中高处的安防摄像头监控整个楼层平面。发布器使用 `LowOverhead` 策略，因为场景变化缓慢，而且必须为音频预留带宽。

**预期结果：** 询问时，角色会描述俯视画面中可见的内容，例如家具布局、人员分布或危险因素。

将俯视摄像机指定给 **目标摄像机** 字段，该字段位于 Inspector 中的 `CameraVisionFrameSource` 组件上。 `CameraVisionFrameSource.TargetCamera` 具有私有 setter，因此脚本无法在运行时将帧源重新指向其他摄像机；Inspector 字段是选择读取哪个摄像机的唯一受支持方式。

```csharp
using Convai.Modules.Vision;
using Convai.Runtime.Vision.Publishing;
using UnityEngine;

/// <summary>
/// 配置发布策略，适用于俯视安防摄像机已在 Inspector 中
/// 指定给 CameraVisionFrameSource 的 Target Camera 字段的场景。
/// 挂载到 ConvaiVisionRoot GameObject。
/// </summary>
public class SecurityCameraVisionSetup : MonoBehaviour
{
    [SerializeField] private ConvaiVisionPublisher _publisher;

    void Awake()
    {
        // 低开销策略：5 fps、350 kbps，适用于变化缓慢的场景
        _publisher.SetPublishPolicy(VisionPublishPolicy.LowOverhead);
    }
}
```

### 玩家注视时激活发布

持续传输视觉内容的开销很高。此模式仅在玩家注视特定物体（例如一台机器）时激活发布，其他情况下则暂停发布。

**预期结果：** 只有玩家注视物体时，角色才会对其状态作出响应。玩家移开视线后，网络和 GPU 开销均为零。

```csharp
using Convai.Modules.Vision;
using Convai.Runtime.Vision.Publishing;
using UnityEngine;

/// <summary>
/// 玩家注视指定物体时激活视觉内容发布。
/// 挂载到目标物体。ConvaiVisionPublisher 必须设置为 Manual 策略。
/// </summary>
public class LookAtVisionTrigger : MonoBehaviour
{
    [SerializeField] private ConvaiVisionPublisher _publisher;
    [SerializeField] private Camera _playerCamera;
    [SerializeField] private float _maxViewAngle = 15f;

    void Awake()
    {
        _publisher.SetPublishPolicy(VisionPublishPolicy.Manual);
    }

    void Update()
    {
        Vector3 directionToObject = (transform.position - _playerCamera.transform.position).normalized;
        float angle = Vector3.Angle(_playerCamera.transform.forward, directionToObject);
        bool isLooking = angle < _maxViewAngle;

        if (isLooking && !_publisher.IsPublishing)
            _publisher.EnablePublishing(true);
        else if (!isLooking && _publisher.IsPublishing)
            _publisher.EnablePublishing(false);
    }
}
```

### 为 WebGL 配置视觉功能

在 WebGL 上，无需帧源组件。 `ConvaiVisionPublisher` 会自动通过 `canvas.captureStream()`捕获浏览器画布。将 **连接类型** 设为 **视频** 并根据需要设置发布策略，其余均由系统自动处理。

**预期结果：** 角色会接收浏览器画布的实时画面。场景中无需添加帧源组件。

```csharp
using Convai.Modules.Vision;
using Convai.Runtime.Vision.Publishing;
using UnityEngine;

/// <summary>
/// WebGL 专用设置。无需帧源，发布器会使用 canvas.captureStream()。
/// 附加到与 ConvaiVisionPublisher 相同的 GameObject。
/// 在 Play 之前，将 ConvaiRoomManager.ConnectionType 设为 Video。
/// </summary>
public class WebGLVisionSetup : MonoBehaviour
{
    [SerializeField] private ConvaiVisionPublisher _publisher;

    void Awake()
    {
        // LowOverhead 适用于 WebGL：画布捕获帧率上限为 15 fps
        _publisher.SetPublishPolicy(VisionPublishPolicy.LowOverhead);
    }
}
```

{% hint style="danger" %}
**WebGL 上必须使用 HTTPS。** 这个 `canvas.captureStream()` 在非 HTTPS 来源上，浏览器会阻止 API。请先将 WebGL 构建部署到 HTTPS 主机，再在生产环境中测试 Vision。 `http://localhost` 是唯一的例外。
{% endhint %}

### 按需触发 Vision 并调整响应模式

前面的示例都通过 `ConvaiVisionPublisher`持续发布帧。 `IConvaiRoomConnectionService` 上还提供了一个独立的低级接口，可让你按需请求后端检查缓冲帧，不受发布器自身频率的影响，并控制检查是否会触发角色发言。这种模式适用于“现在看一看”按钮、由玩家手动触发的检查工具，或需要在精确时刻执行 Vision 检查的脚本序列步骤。

`RequestVisionStatus()` 会请求后端报告会话帧缓冲区的状态。 `TriggerVision(ConvaiVisionTriggerRequest)` 会请求后端将缓冲帧附加到下一轮交互中，并根据请求的响应模式调用模型。 `UpdateRespondMode(ConvaiRespondModeLane, ConvaiRespondMode)` 会更改整个输入通道在会话剩余时间内对角色语音的影响方式。这三个方法都通过领域事件异步确认，而不是返回值；完整的方法签名、请求字段和事件负载请参阅 [Vision 脚本 API](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/vision/scripting-api.md) 。

**预期结果：** 调用 `RequestLookNow()` 会记录缓冲区状态，随后角色会描述发生的变化并给出回答。调用 `SilenceVisionUntilAsked()` 会阻止角色对新的 Vision 帧作出反应，直到再次调用 `RequestLookNow()` 。

```csharp
using Convai.Domain.DomainEvents.Vision;
using Convai.Domain.EventSystem;
using Convai.Runtime;
using Convai.Runtime.Components;
using Convai.Runtime.Room;
using Convai.Runtime.Vision.Context;
using UnityEngine;

/// <summary>
/// 在发布器的常规帧频率之外请求按需执行 Vision 检查，
/// 然后报告缓冲区状态和触发结果。可附加到场景中的任意对象。
/// </summary>
public class OnDemandVisionInspector : MonoBehaviour
{
    private IConvaiRoomConnectionService _roomService;
    private SubscriptionToken _statusToken;
    private SubscriptionToken _triggerToken;

    void OnEnable()
    {
        ConvaiManager manager = ConvaiManager.ActiveManager;
        if (manager == null || !manager.TryGetRoomConnectionService(out _roomService))
            return;

        if (!manager.TryGetEventHub(out IEventHub hub))
            return;

        _statusToken = hub.Subscribe<VisionContextStatusReceived>(OnVisionStatus, EventDeliveryPolicy.MainThread);
        _triggerToken = hub.Subscribe<VisionContextTriggerReceived>(OnVisionTriggerAck, EventDeliveryPolicy.MainThread);
    }

    void OnDisable()
    {
        if (ConvaiManager.ActiveManager == null || !ConvaiManager.ActiveManager.TryGetEventHub(out IEventHub hub))
            return;

        hub.Unsubscribe(_statusToken);
        hub.Unsubscribe(_triggerToken);
    }

    // 在“现在看一看”UI 按钮的回调中调用
    public void RequestLookNow()
    {
        _roomService?.RequestVisionStatus();
        _roomService?.TriggerVision(new ConvaiVisionTriggerRequest
        {
            Text = "自上次查看以来，工作台上有什么变化？",
            RespondMode = ConvaiRespondMode.MustRespond
        });
    }

    // 调用一次，例如玩家进入一个会因 Vision 响应而分心的区域时
    public void SilenceVisionUntilAsked()
    {
        _roomService?.UpdateRespondMode(ConvaiRespondModeLane.Vision, ConvaiRespondMode.Silent);
    }

    private void OnVisionStatus(VisionContextStatusReceived status)
    {
        Debug.Log($"[Vision] {status.Outcome} — last frame age: {status.LastFrameAgeMs} ms (source: {status.ActiveSourceLabel})");
    }

    private void OnVisionTriggerAck(VisionContextTriggerReceived ack)
    {
        if (ack.Downgraded)
            Debug.Log($"[Vision] Trigger downgraded to {ack.ActualRespondMode}: {ack.DowngradeReason}");
        else if (ack.LlmTriggered)
            Debug.Log($"[Vision] Character responded using {ack.FramesAttached} frame(s).");
    }
}
```

`RequestLookNow()` 上面的代码会构建一个新的 `ConvaiVisionTriggerRequest` 且未显式指定 `UpdateId` 的请求，每次调用都会如此。因此，在收到确认消息丢失后再次调用它，会发送一个不同的触发请求，而不是安全地重放原请求——每次调用都会生成各自的 ID。若要让重试具有幂等性，请预先生成一个 `UpdateId` ID，传入构造函数，并在重试时重复使用同一个值；这样，后端会针对该 ID 重放原始确认消息，而不会再次触发。请参阅 [Vision scripting API](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/vision/scripting-api.md#convaivisiontriggerrequest) 了解构造函数签名。

### 后续步骤

{% content-ref url="/pages/9ee175b12da238182d707abd778abdc3a8706c80" %}
[Vision 脚本 API](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/vision/scripting-api.md)
{% endcontent-ref %}

{% content-ref url="/pages/86612bc613c5a299a468b71b3fb8a40e625ee1fe" %}
[排查视觉问题](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/vision/troubleshooting-and-diagnostics.md)
{% endcontent-ref %}

{% content-ref url="/pages/cb7758289bc48a93210bce51933fd819fd05e245" %}
[自定义帧来源](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/vision/custom-frame-sources.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/features/vision/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.
