> 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/scene-metadata/scripting-api-reference.md).

# 场景元数据脚本 API

Scene Metadata 类的完整 C# 参考，涵盖物体属性、追踪属性更新、注册表查询和手动发送触发器。

场景元数据脚本接口由三个部分组成。 `ConvaiObjectMetadata` 是附加在每个场景对象上的组件，可用于在运行时读取和更新对象属性及跟踪属性。 `ConvaiMetadataRegistry` 是静态中央注册表，可用于查询注册状态并监听变更。 `ConvaiSceneMetadataCollector` 是运行时协调器，可用于触发收集、检查就绪状态以及审查所有已注册对象。

### ConvaiObjectMetadata

`ConvaiObjectMetadata` 是一个 `MonoBehaviour` ，可通过序列化字段或 `GetComponent<ConvaiObjectMetadata>()`访问。有关 Inspector 字段、生命周期和验证规则，请参阅 [场景元数据组件参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/scene-metadata/component-reference.md).

#### 属性

| 成员                  | 类型       | 说明                                                    |
| ------------------- | -------- | ----------------------------------------------------- |
| `ObjectName`        | `string` | 可读写。对象的显示名称。在对象已注册时设置新值，会将更改重新同步到所有已连接的角色。            |
| `ObjectDescription` | `string` | 可读写。对象的描述文本。与 `ObjectName`.                           |
| `IncludeInMetadata` | `bool`   | 可读写。指定下次收集元数据时是否包含此对象。与 `ObjectName`.                 |
| `IsRegistered`      | `bool`   | 只读。当前组件已在 `true` 表示当前组件已注册到 `ConvaiMetadataRegistry`. |
| `IsValid`           | `bool`   | 只读。 `true` 表示 `ObjectName` 非空且不全为空白字符。                |

{% hint style="info" %}
在对象已注册时，设置 `ObjectName`, `ObjectDescription`或 `IncludeInMetadata` 会自动将新值重新同步到所有已连接的角色，无需手动发送。本页后面的运行时对象排除模式仍会在设置 `CollectAndSendSceneMetadata()` 后显式调用 `IncludeInMetadata`；对于属性变更本身，这个调用现在已是多余的，但如果希望强制立即发送并在控制台记录日志，仍可使用它。
{% endhint %}

#### 方法

| 方法                                                                                                                  | 返回              | 说明                                                                                                                                                                         |
| ------------------------------------------------------------------------------------------------------------------- | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `SetTrackedPropertyValue(string propertyName, string value, ConvaiRespondMode reaction = ConvaiRespondMode.Silent)` | `void`          | 更新一个跟踪属性，并立即将新值推送给所有已连接的角色。此方法是通过命令式调用更新跟踪属性的方式，与从 Inspector 的 `跟踪属性` 列表中轮询跟踪属性的方式相对应。当值通过代码更改时，可调用此方法，而不必依赖自动轮询。 `reaction` 控制更新是否可以使角色说话；默认为 `ConvaiRespondMode.Silent`. |
| `BuildStateKey(string propertyName)`                                                                                | `string`        | 返回此对象上已跟踪属性的动态上下文状态键，格式为 `"{ObjectName}.{propertyName}"`.                                                                                                                  |
| `GetValidationErrors()`                                                                                             | `List<string>`  | 返回以下属性的验证错误消息： `ObjectName` （必填，最多 50 个字符）和 `ObjectDescription` （最多 200 个字符）。元数据有效时返回空值。                                                                                   |
| `ToSceneMetadata()`                                                                                                 | `SceneMetadata` | 将此组件的 `ObjectName` 和 `ObjectDescription` 转换为 RTVI 消息内部使用的可序列化负载类型。                                                                                                         |

**推送已跟踪属性更新：**

{% code title="Door.cs" %}

```csharp
public class Door : MonoBehaviour
{
    [SerializeField] private ConvaiObjectMetadata _metadata;
    private bool _isOpen;

    public void ToggleDoor()
    {
        _isOpen = !_isOpen;
        _metadata.SetTrackedPropertyValue("State", _isOpen ? "open" : "closed");
    }
}
```

{% endcode %}

### ConvaiMetadataRegistry

`ConvaiMetadataRegistry` 是一个静态类。可直接通过类名访问所有成员，无需实例或组件引用。

#### 属性

| 成员      | 类型    | 说明                                            |
| ------- | ----- | --------------------------------------------- |
| `Count` | `int` | 已注册的 `ConvaiObjectMetadata` 实例总数，包括无效和已禁用的实例。 |

#### 方法

| 方法                        | 返回                           | 说明                                                                                                                          |
| ------------------------- | ---------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| `GetAllMetadata()`        | `ConvaiObjectMetadata[]`     | 返回所有已注册的实例，包括名称为空、 `Include In Metadata`已禁用或为空引用的实例。                                                                        |
| `GetValidMetadata()`      | `ConvaiObjectMetadata[]`     | 仅返回非空、 `Include In Metadata` 已启用且通过名称验证（`IsValid == true`）的实例。这正是下一次发送时包含的实例集合。                                             |
| `GetSceneMetadataList()`  | `List<SceneMetadata>`        | 将所有有效元数据转换为可序列化的传输格式。这是发送给 Convai 的负载。                                                                                      |
| `GetStatistics()`         | `Dictionary<string, object>` | 返回包含以下键的统计明细： `TotalRegistered`, `ValidMetadata`, `InvalidMetadata`, `NullReferences`, `ValidNames`, `InvalidReasons`。用于调试。 |
| `CleanupNullReferences()` | `int`                        | 移除已销毁但尚未注销的条目。返回移除的条目数。如果对象是在 Unity 常规生命周期事件之外销毁的，请调用此方法。                                                                   |
| `Clear()`                 | `void`                       | 清除所有已注册条目。用于测试和场景 teardown。请勿在生产环境中调用。                                                                                      |

#### 静态事件

| 事件                       | 签名                             | 触发时机                                     |
| ------------------------ | ------------------------------ | ---------------------------------------- |
| `OnMetadataRegistered`   | `Action<ConvaiObjectMetadata>` | 某个 `ConvaiObjectMetadata` 组件启用并完成自身注册。   |
| `OnMetadataUnregistered` | `Action<ConvaiObjectMetadata>` | 某个 `ConvaiObjectMetadata` 组件停用或销毁，并注销自身。 |

```csharp
void OnEnable()
{
    ConvaiMetadataRegistry.OnMetadataRegistered += HandleObjectRegistered;
    ConvaiMetadataRegistry.OnMetadataUnregistered += HandleObjectUnregistered;
}

void OnDisable()
{
    ConvaiMetadataRegistry.OnMetadataRegistered -= HandleObjectRegistered;
    ConvaiMetadataRegistry.OnMetadataUnregistered -= HandleObjectUnregistered;
}

private void HandleObjectRegistered(ConvaiObjectMetadata metadata)
{
    Debug.Log($"Registered: {metadata.ObjectName} ({ConvaiMetadataRegistry.Count} total)");
}

private void HandleObjectUnregistered(ConvaiObjectMetadata metadata)
{
    Debug.Log($"Unregistered: {metadata.ObjectName}");
}
```

### ConvaiSceneMetadataCollector

通过组件引用访问。 `ConvaiManager` 会在启动时注入依赖，无需手动设置。

```csharp
private ConvaiSceneMetadataCollector _collector;

void Awake()
{
    _collector = FindObjectOfType<ConvaiSceneMetadataCollector>();
}
```

#### 公共方法

| 方法                              | 返回                    | 说明                                                                                                                        |
| ------------------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| `IsReadyToSendMetadata()`       | `bool`                | 当依赖已注入且房间会话处于 `true` 状态时返回 `Connected` 。手动调用 `CollectAndSendSceneMetadata()` 之前，务必先检查此状态。                                 |
| `CollectAndSendSceneMetadata()` | `void`                | 从 `ConvaiMetadataRegistry`读取所有有效元数据，组装负载，并通过 RTVI `update-scene-metadata` 消息发送给 Convai。如果房间未连接或依赖尚未注入，则提前返回，并在控制台记录警告或错误。 |
| `GetMetadataCount()`            | `int`                 | 返回有效且可纳入的对象数量，但不会触发发送。可用于界面显示或发送前验证。                                                                                      |
| `GetCurrentMetadata()`          | `List<SceneMetadata>` | 返回当前载荷列表，但不会触发发送。可用于检查下次调用时将要发送的内容。                                                                                       |
| `ValidateAllMetadata()`         | `void`                | 将所有已注册对象的验证问题记录到 Console。在开发过程中使用此方法，可发现缺失名称、长度超限或已禁用的对象。                                                                 |

#### 常见模式

**场景加载时手动触发：**

```csharp
IEnumerator LoadScenario(ScenarioData data)
{
    yield return StartCoroutine(SpawnScenarioProps(data));

    // Wait until room is ready
    yield return new WaitUntil(() => _collector.IsReadyToSendMetadata());
    _collector.CollectAndSendSceneMetadata();
}
```

**运行时排除对象并重新发送：**

```csharp
// Remove a locked door from AI context when it opens
void OnDoorUnlocked(ConvaiObjectMetadata doorMetadata)
{
    doorMetadata.IncludeInMetadata = false;
    if (_collector.IsReadyToSendMetadata())
        _collector.CollectAndSendSceneMetadata();
}
```

**发送前审计：**

```csharp
void LogPreSendAudit()
{
    _collector.ValidateAllMetadata(); // prints all issues to Console
    Debug.Log($"Will send {_collector.GetMetadataCount()} objects");

    var preview = _collector.GetCurrentMetadata();
    foreach (var item in preview)
        Debug.Log($"  - {item.Name}: {item.Description}");
}
```

**调试统计：**

```csharp
var stats = ConvaiMetadataRegistry.GetStatistics();
foreach (var kv in stats)
    Debug.Log($"{kv.Key}: {kv.Value}");
```

### 后续步骤

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

{% content-ref url="/pages/f6f3f3d88a3636afea1b0c8774162c2014fba780" %}
[排查场景元数据问题](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/scene-metadata/troubleshooting-and-diagnostics.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/scene-metadata/scripting-api-reference.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.
