> 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/character-actions/update-actions-at-runtime.md).

# 在运行时更新角色动作

在会话进行中发送一个动作配置补丁，跟踪其更新 ID，并在确认后端已确认之前不要假定更改已生效。

使用 `ConvaiActionConfigPatch` 与 `ConvaiCharacter.DynamicContext.Apply` 可在不断开会话的情况下，替换已连接角色的动作、物体、角色或注意目标。场景状态在连接后发生变化时（例如出现了新物体，或目标变得不可用），可使用此功能让角色的可交互能力及时更新。只有在 Convai 针对其更新 ID 返回成功确认后，补丁才会生效。

### 前提条件

* 一个 `ConvaiCharacter` 已连接（`IsInConversation` 返回 `true`).
* 本地 `ConvaiActionDefinition` 条目必须已为补丁新增的任何动作名称注册——补丁中的动作名称必须与本地可执行的定义匹配，无论该定义来自内联定义还是可复用的 Action Set（请参阅 [配置角色动作](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/character-actions/configuring-actions.md)），否则整个更新会在发送前被拒绝。
* 请先熟悉 [配置角色动作](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/character-actions/configuring-actions.md).

### 发送运行时动作补丁

{% stepper %}
{% step %}

#### 构建补丁

仅设置要更改的字段。 `ConvaiActionConfigPatch` 采用省略与空值语义： `null` 字段会保留已确认的值，空列表或空字符串会清除该值，非空值则会替换该值。

```csharp
using System.Collections.Generic;
using Convai.Shared.Actions;

var patch = new ConvaiActionConfigPatch
{
    Objects = new List<ConvaiActionObjectDefinition>
    {
        new()
        {
            Name = "Lever",
            Description = "Metal wall lever.",
            GameObjectReference = leverGameObject
        }
    }
};
```

| 字段                       | `null` （省略） | 空列表或字符串  | 非空值                                                     |
| ------------------------ | ----------- | -------- | ------------------------------------------------------- |
| `Actions`                | 保留已确认的动作列表  | 清除请求级动作  | 替换已确认的动作列表                                              |
| `Objects`                | 保留已确认的物体    | 清除已确认的物体 | 替换已确认的物体。同名替换项在新条目未设置 `GameObjectReference` 时，会继承现有的本地值 |
| `Characters`             | 保留已确认的角色    | 清除已确认的角色 | 替换已确认的角色                                                |
| `CurrentAttentionObject` | 保留注意目标      | 清除注意目标   | 设置注意目标。必须与以下内容中的某个名称匹配 `Objects` 替换应用后                  |

替换 `Objects` 如果某个过时的注意目标已不存在，则会自动清除该目标。
{% endstep %}

{% step %}

#### 发送补丁

将补丁传递给 `DynamicContext.Apply` 并明确指定 `updateId` 以便关联后端确认结果：

```csharp
using Convai.Runtime;
using Convai.Runtime.DynamicContext;

character.DynamicContext.Apply(new ConvaiDynamicContextUpdate(
    text: null,
    reaction: ConvaiRespondMode.Silent,
    currentAttentionObject: "Lever",
    updateId: "lever-unlock-01",
    actionConfig: patch));
```

{% hint style="warning" %}
发送补丁不会立即更改 `ConvaiCharacter.ActionConfig` 。确认结果会按更新发送的顺序提交。出现错误状态、确认结果不匹配、断开连接或超过 30 秒确认超时时，待处理的变更会被丢弃，不会重试 — `ActionConfig` 始终反映后端最近确认的快照，而不是你最近发送的补丁。
{% endhint %}
{% endstep %}
{% endstepper %}

### 跟踪更新 ID

请自行提供 `updateId` 作为 `ConvaiDynamicContextUpdate` 的参数，而不要依赖 SDK 自动生成的 ID。当 `updateId` 被省略时，SDK 会生成一个内部 ID 用于跟踪，但不会将其返回给调用方，因此你无法将它与之后收到的确认结果关联起来。

一个 `updateId` 一次只能有一个待确认的运行时操作变更。发送第二个补丁时，如果其 `updateId` 仍在等待确认，本地会拒绝该补丁并在控制台发出警告；请等待第一个更新完成，或使用不同的 `updateId`.

### 读取后端确认结果

订阅 `ConvaiManager.ActiveManager.Events.OnDynamicContextUpdateResultReceived` 并根据你发送的 `updateId` 进行筛选：

```csharp
using Convai.Domain.DomainEvents.Runtime;
using Convai.Runtime.Components;

ConvaiManager.ActiveManager.Events.OnDynamicContextUpdateResultReceived += result =>
{
    if (result.UpdateId != "lever-unlock-01")
        return;

    if (result.Status == "success")
    {
        Debug.Log($"Actions confirmed: objects={result.ObjectsCount}, attention={result.CurrentAttentionObject}");
    }
    else
    {
        Debug.LogWarning($"Action patch failed: {result.Status}");
    }
};
```

`DynamicContextUpdateResultReceived` 除了通用动态上下文字段外，还包含有关操作更新的类型化元数据：

| 属性                                                | 类型        | 含义                                    |
| ------------------------------------------------- | --------- | ------------------------------------- |
| `UpdateId`                                        | `string`  | 你在 `ConvaiDynamicContextUpdate`.      |
| `Status`                                          | `string`  | `"success"` 补丁应用时；任何其他值都表示补丁已被拒绝。     |
| `ActionConfigUpdated`                             | `bool?`   | 此确认是否包含操作配置变更。                        |
| `ActionConfigCreated`                             | `bool?`   | 后端是否为该会话创建了新的操作配置。                    |
| `ActionsCount`, `ObjectsCount`, `CharactersCount` | `int?`    | 补丁应用后，已确认配置中的最终计数。                    |
| `CurrentAttentionObject`                          | `string`  | 补丁应用后的最终注意对象。                         |
| `CurrentAttentionObjectCleared`                   | `bool?`   | 此更新是否清除了注意对象。                         |
| `ActionGenerationStrategyChanged`                 | `bool?`   | 后端的操作生成策略是否发生了变化。                     |
| `ActionGenerationStrategyStatus`                  | `string`  | 策略变更的状态字符串，包括 `"requires_reconnect"`. |
| `RawExtras`                                       | `JObject` | 尚未作为类型化属性公开的字段所对应的原始后端负载。             |

当 `ActionGenerationStrategyStatus` 为 `"requires_reconnect"`时，SDK 会公开该状态，但不会自动重新连接——如果新策略需要重新连接，请自行重新连接会话。

如需在代码中发送补丁前预览其预测结果，请使用“操作调试”窗口中的运行时补丁组合器，详见 [排查角色操作问题](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/character-actions/debugging-and-troubleshooting.md).

### 故障排查

#### 补丁在发送前被拒绝

**症状：** 控制台出现一条指出字段名称的警告，例如 `action_config action '...' has no local executable definition` 或 `duplicate action target name '...'`.

**原因：** 补丁在本地验证时未通过——操作名称没有匹配的本地 `ConvaiActionDefinition`，目标名称为空或重复，或者当前注意对象与补丁中的对象无法匹配。

**解决方法：** 修正警告中指出的字段，并使用新的 `updateId`.

**验证：** 控制台不再显示拒绝警告，并且 `OnDynamicContextUpdateResultReceived` 随后会针对同一个 `updateId`.

#### 始终未收到确认

**症状：** `OnDynamicContextUpdateResultReceived` 始终不会针对该项触发 `updateId` 你发送的，并且 `ConvaiCharacter.ActionConfig` 不会反映此补丁。

**原因：** 更新在 30 秒确认超时、ACK 错误或确认元数据格式错误/不匹配后被丢弃——在这些情况下，控制台会记录 `Runtime action mutation discarded update_id=<id> reason=<reasonCode>` 。如果会话在 Convai 响应之前断开连接，更新也会被丢弃，但不会显示任何控制台消息。被丢弃的更新不会自动重试。

**解决方法：** 确认角色已连接后，使用新的 `updateId` 重新发送补丁（`IsInConversation` 为 `true`).

**）。验证：** `OnDynamicContextUpdateResultReceived` 触发，且 `Status == "success"` 对应新的 `updateId`.

### 后续步骤

{% content-ref url="/pages/5b02ee57da9de48585f7ea92aa9e94714547d80a" %}
[动作目标解析的工作方式](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/character-actions/attention-and-reference-grounding.md)
{% endcontent-ref %}

{% content-ref url="/pages/1398e3302b345ef93934a0e6c93b4d8e576ab00e" %}
[排查角色动作问题](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/character-actions/debugging-and-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 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/character-actions/update-actions-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.
