> 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-unreal-engine-plugin/features/scene-metadata/managing-the-environment-at-runtime.md).

# 运行时管理环境

用于 chatbot 环境方法的参考，这些方法在活动游戏会话期间添加、移除和更新对象和角色。

使用这些方法可在游戏运行时更新聊天机器人的世界知识，例如加载新房间、生成道具或新的 NPC 进入场景时。 `UConvaiChatbotComponent` 提供用于修改对象、角色、当前对话对象、注意对象以及连接时环境附加信息的方法。运行时修改方法属于 `BlueprintCallable` 中的 `Convai|Actions` 类别； `GatherEnvironmentExtras` 属于 `BlueprintCallable` 中的 `Convai|Session` 类别。

### 方法组一览

| 分组   | 方法                                                                                             | 用途                                |
| ---- | ---------------------------------------------------------------------------------------------- | --------------------------------- |
| 对象   | `AddObject`, `AddObjects`, `RemoveObject`, `RemoveObjects`, `ClearObjects`                     | 在会话期间添加或移除世界对象                    |
| 角色   | `AddCharacter`, `AddCharacters`, `RemoveCharacter`, `RemoveCharacters`, `ClearCharacters`      | 添加或移除聊天机器人可提及的其他 NPC              |
| 对话对象 | `SetConversationPartner`                                                                       | 告知聊天机器人正在与谁交谈                     |
| 注意对象 | `SetObjectInAttention`, `TrySetObjectInAttentionFromGaze`, `TryClearObjectInAttentionFromGaze` | 设置、通过注视门控设置或清除注意对象                |
| 会话开始 | `GatherEnvironmentExtras`                                                                      | 在 `/connect`                      |
| 实用工具 | `EnsureObjectComponentsForEnvironmentObjects`                                                  | 生成缺失的 `UConvaiObjectComponent` 实例 |

大多数用于推送网络更新的方法都接受一个 `bFlushImmediately` 参数。 `TryClearObjectInAttentionFromGaze` 会通过非立即路径清除。详情请参阅 [防抖与刷新](#debounce-and-flush) 。

### 这个 `FConvaiEnvironmentData` 结构体

`EnvironmentData` (`FConvaiEnvironmentData`）是 `UConvaiChatbotComponent` 在 `/connect` 时发送给 Convai 的静态配置。它包含：

* `bEnableActions` (`bool`，默认值为 `true`）— 连接时的操作配置开关。当 `false`时， `action_config` 块不会在 `/connect`时发送，并且通过 `SetObjectInAttention` 解析注意对象不会产生任何效果。
* `Actions` — 默认操作列表（`Move To`, `Follow`, `Stop Moving`, `Wait For`).
* `Objects` — 连接时向聊天机器人公开的对象。
* `Characters` — 连接时向聊天机器人公开的角色。
* `CurrentAttentionObject` — 当前用于注意和引用解析的对象。

请通过以下方法修改环境，而不要直接在 Blueprint 中写入 `EnvironmentData` 字段。

### 添加和移除对象

| 方法                                              | 说明                                                                            |
| ----------------------------------------------- | ----------------------------------------------------------------------------- |
| `AddObject(Object, bFlushImmediately)`          | 添加一个 `FConvaiObjectEntry` ，并在该对象不属于连接时快照的情况下，安排推送一次 `update-scene-metadata` 。 |
| `AddObjects(Objects, bFlushImmediately)`        | 一次调用即可添加多个条目。                                                                 |
| `RemoveObject(ObjectName, bFlushImmediately)`   | 移除与给定名称匹配的条目，并安排同步。                                                           |
| `RemoveObjects(ObjectNames, bFlushImmediately)` | 按名称移除多个条目。                                                                    |
| `ClearObjects(bFlushImmediately)`               | 从本地列表中移除所有对象。                                                                 |

{% hint style="warning" %}
如果某个对象已包含在 `action_config` 中的 `/connect`，则在会话中途使用相同名称调用 `AddObject` 不会更新已冻结的 `action_config` 快照。只有会话中新添加的对象才会通过实时 `update-scene-metadata` 通道传输。若要将描述更改同步到现有对象，请调用 `StopSession` 然后调用 `StartSession` 以重新连接。
{% endhint %}

### 添加和移除角色

| 方法                                                      | 说明                                |
| ------------------------------------------------------- | --------------------------------- |
| `AddCharacter(Character, bFlushImmediately)`            | 将一个 `FConvaiObjectEntry` 添加到角色列表。 |
| `AddCharacters(Characters, bFlushImmediately)`          | 添加多个条目。                           |
| `RemoveCharacter(InCharacterName, bFlushImmediately)`   | 按名称移除匹配的条目。                       |
| `RemoveCharacters(InCharacterNames, bFlushImmediately)` | 按名称移除多个条目。                        |
| `ClearCharacters(bFlushImmediately)`                    | 从本地列表中移除所有角色。                     |

### 设置对话对象

`SetConversationPartner(Partner, bFlushImmediately)` 告知聊天机器人当前正在与哪个其他角色对话。如果 `Partner.Name` 尚未包含在 `EnvironmentData.Characters`中，该方法会自动将其添加。

若要清除对话对象但不将该角色从列表中移除，请传入一个 `FConvaiObjectEntry` ，其 `Name`.

### 控制注意力

`SetObjectInAttention(Object, Text, ShouldRespond, bFlushImmediately)` 设置聊天机器人当前关注的对象，并可选择触发上下文事件。当 `bEnableActions` 为 `false`。如果对象尚未位于对象列表中，该方法会自动将其添加进去。

`AttentionSource` (`EConvaiAttentionSource`, `Transient`, `BlueprintReadOnly`，类别为 `Convai|Actions`) 反映了最近一次设置注意力的来源：

* `None` — 未设置注意力目标。
* `Explicit` (`Explicit (Blueprint/C++)`) — 注意力由 Blueprint 或 C++ 代码设置。
* `Gaze` — 注意力由注视管线设置。

当 `AttentionSource` 为 `Explicit`时，对 `TrySetObjectInAttentionFromGaze` 的调用会被阻止并返回 `false`。这样可以防止注视系统覆盖显式设置的程序化注意力。

`TryClearObjectInAttentionFromGaze(ExpectedObject)` 仅当 `AttentionSource` 为 `Gaze` 且当前注意力对象仍与 `ExpectedObject.Name`匹配时，才会清除由注视设置的注意力槽位。这样可以避免较早目标的注视结束事件延迟到达时，清除较新的注意力目标。

### 在会话开始时填充环境

当关卡是程序化生成的，或者需要通过运行时世界查询来构建对象列表，而不是在“细节”面板中手动放置组件时，请使用 `GatherEnvironmentExtras` 。

`GatherEnvironmentExtras` 是一个 `BlueprintNativeEvent` （显示名称为 `"Gather Environment Extras"`），在 `StartSession()` 内部、 `/connect` 握手之前调用一次。可在 `UConvaiChatbotComponent` 的 Blueprint 子类中重写此事件，以追加依赖运行时世界状态的对象、角色或动作。

重写函数会接收三个输出数组：

* `OutExtraActions` — 追加到默认操作列表中。
* `OutExtraObjects` — 追加到 `EnvironmentData.Objects`.
* `OutExtraCharacters` — 追加到 `EnvironmentData.Characters`.

此覆盖项会在已配置的默认值基础上追加内容，而不是替换它们。应在此处通过世界查询填充环境，而不是通过 Details 面板填充。

有关此模式的完整伪代码示例，请参阅 [场景元数据用法示例](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unreal-engine-plugin/features/scene-metadata/scene-metadata-usage-examples.md) 。

### 确保对象组件存在

`EnsureObjectComponentsForEnvironmentObjects()` 会遍历 `EnvironmentData.Objects`。对于每个具有有效 `Ref` Actor 的条目，如果尚无组件覆盖同一目标，就会生成匹配的 `UConvaiObjectComponent` 。该函数会返回新生成的组件数量，并且可以安全地多次调用（具有幂等性）。

自动生成的组件会注册到子系统级对象池中，因此关卡中的每个聊天机器人都能通过与手动放置的对象组件相同的空间感知、属性跟踪和注视流程发现它们。

请在 `BeginPlay` 中填充 `EnvironmentData.Objects` （通过代码），或在调用 `AddObject` / `AddObjects` 后调用此函数，以便让 [空间感知](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unreal-engine-plugin/features/spatial-awareness.md) 和注视系统跟踪动态添加的 Actor。

### 防抖与刷新

所有变更方法都会在防抖时间窗口内批量处理更新，将快速连续的调用合并为一条 WebRTC 消息。设置 `bFlushImmediately = true` 可跳过该时间窗口并立即发送。请谨慎使用 `bFlushImmediately` ——高频调用会产生大量小消息，增加网络开销。

### 后续步骤

{% content-ref url="/pages/7fc985238017f8bd9de6df276f318c98902cac03" %}
[场景元数据使用示例](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unreal-engine-plugin/features/scene-metadata/scene-metadata-usage-examples.md)
{% endcontent-ref %}

{% content-ref url="/pages/35be910ed18e7f78411fd4d732770d70307e1434" %}
[排查场景元数据问题](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unreal-engine-plugin/features/scene-metadata/troubleshoot-scene-metadata.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-unreal-engine-plugin/features/scene-metadata/managing-the-environment-at-runtime.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.
