> 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/writing-custom-executors.md).

# 编写自定义动作执行器

通过编写自己的执行器组件，将自定义移动、库存、UI 或物理行为连接到 Convai 动作管道。

当内置执行器与项目的移动系统、交互模型或游戏规则不匹配时，请实现 `IConvaiActionExecutor`。自定义执行器是一个标准的 C# `MonoBehaviour` ，其中包含一个异步方法。调度器对待它的方式与内置执行器完全相同——所有策略、事件和取消行为都会自动生效。

### 何时创建自定义执行器

在以下情况下创建自定义执行器：

* 项目使用了自定义移动系统（根运动、 `CharacterController`、转向行为）
* 某个操作会修改物品栏、UI 状态、任务标记或物理对象
* 某个操作会调用外部服务，或触发基于协程的动画系统
* 需要条件逻辑——例如，根据角色状态执行不同行为的操作
* 该操作用于查明某些信息，而非执行可见动作——请参阅下文的 [回答问题，而不是执行操作](#answer-a-question-instead-of-acting) 。

### IConvaiActionExecutor 接口

```csharp
public interface IConvaiActionExecutor
{
    Task<ConvaiActionExecutionResult> ExecuteAsync(
        ConvaiActionInvocation invocation,
        CancellationToken cancellationToken);
}
```

在任意 `MonoBehaviour`上实现此接口。调度器会为每个步骤调用 `ExecuteAsync` ，并等待其结果后再继续下一个步骤。请让任务保持运行，直到游戏逻辑处理完毕——即使动画或移动仍在进行，提前返回也会结束该步骤。

{% hint style="info" %}
执行器在 Unity 主线程上运行。你可以在`transform`, `GetComponent`, `Instantiate`等 Unity API）中安全调用这些 API。可在 `ExecuteAsync`内的任意位置调用。使用 `await Task.Yield()` 可以让出一帧，同时留在主线程上。
{% endhint %}

### 选择基类，而不是直接使用原始接口

所有随产品发布的执行器都继承自 `ConvaiActionExecutorBase` ，而不是直接实现 `IConvaiActionExecutor` ；你自己的自定义执行器也应如此。继承基类后，组件会自动获得 Convai 检视面板（分区字段、工具提示和操作绑定状态区块），无需编写任何编辑器代码。

| 基类                                     | 适用场景                                      | 提供的功能                                                              |
| -------------------------------------- | ----------------------------------------- | ------------------------------------------------------------------ |
| `ConvaiActionExecutorBase`             | 需要完全手动控制调用                                | `CharacterTransform`, `ResolvePlayer()`, `DeclaredButNotSent(...)` |
| `ConvaiTargetedActionExecutor`         | 该行为通过层级关系中的同级组件（控制器、移动组件或 Rig）对已解析的目标执行操作 | 目标验证、同级组件解析/缓存、仅记录一次的同级组件缺失诊断信息、调用参数覆盖                             |
| `ConvaiCharacterActionExecutor<TPeer>` | 该行为只需要角色上的某个特定组件                          | 全部 `ConvaiTargetedActionExecutor` 添加了，以及已解析的 `TPeer` 组件会直接传递给你的方法  |
| `ConvaiActionExecutor<TParameters>`    | 您希望使用带类型的参数 DTO，而不是手动访问字典                 | 在方法运行前，按名称将调用参数绑定到 `TParameters` 对象                                |

`ConvaiTargetedActionExecutor`, `ConvaiCharacterActionExecutor<TPeer>`，以及 `ConvaiActionExecutor<TParameters>` 都派生自 `ConvaiActionExecutorBase`，因此它们都已经拥有 Convai 检视器和下一节中的成员。使用以下方式对检视器字段进行分组： `ConvaiInspectorSectionAttribute` 并为每个序列化字段添加 `[Tooltip]` ——Convai 检视器会在任何 `ConvaiActionExecutorBase`派生组件上同时呈现这两者。

### 每个 ConvaiActionExecutorBase 都提供的成员

| 成员                                              | 类型                            | 说明                                                                   |
| ----------------------------------------------- | ----------------------------- | -------------------------------------------------------------------- |
| `CharacterTransform`                            | `Transform` （受保护）             | Convai 角色的变换，只解析一次并缓存。对于任何世界空间的读取或写入，请使用此变换，而不是执行器自身的 `transform` 变换 |
| `ResolvePlayer()`                               | `protected virtual Transform` | 玩家的实际位置 — 请参阅 [解析玩家的位置](#resolve-the-players-position) 下文            |
| `DeclaredButNotSent(invocation, parameterName)` | `protected static bool`       | 该操作是否声明了 `parameterName` 而 Convai Character 未为其发送任何值                 |

#### 读取角色的变换，而不是读取你自身的变换

执行器可以位于 Convai Character 本身，也可以位于承载角色行为的子对象上（指定为 **操作行为对象** 位于 `ConvaiActionConfigSource`）。两种布局均受支持，因此执行器绝不能假定其自身的 `GameObject` 是角色的：

```csharp
// 错误 — 对于偏离原点的 behaviors 对象，这并不是角色的位置。
_home = transform.position;

// 正确 — 无论此组件位于何处，这都是 Convai Character 的位置。
_home = CharacterTransform.position;
```

如果某些操作确实表示“此组件所属对象”（例如设置父对象、遍历层级）， `transform` ，使用你自己的 *角色* 仍然没有问题。这里的规则针对的是角色所在的位置。

#### 解析玩家位置

`ResolvePlayer()` 会返回用于测量玩家位置的 Transform。它是 `protected virtual` (`ConvaiActionExecutorBase.cs:113`），因此，如果项目使用分屏、多个角色操控装置或过场动画摄像机，只需重写一次，即可让该层级中的每个执行器对“玩家”指谁达成一致。

底层查找逻辑位于 `ConvaiPlayerBody`，这是一个 `public static` 类（`ConvaiPlayerBody.cs:26`），场景代码也可以使用它，而不必是执行器：

```csharp
Transform player = ConvaiPlayerBody.Resolve();

// 投影到给定高度 — 摄像机位于头部高度，而角色
// 测量与摄像机的距离时，否则会显得稍远。
if (ConvaiPlayerBody.TryResolveFloorPosition(CharacterTransform.position.y, out Vector3 floorPosition))
{
    // 使用 floorPosition
}
```

`ConvaiPlayerBody.Resolve()` 会优先选择场景中的 `ConvaiPlayer` ，然后回退到 `Camera.main`。找到 `ConvaiPlayer`后，它会解析玩家角色操控装置实际移动的 Transform — 即装置内部的 `CharacterController` 或 `Rigidbody` ，而不是预制件根对象 — 因为第一人称控制器通常会让根对象在整个游戏过程中停留在生成点。读取根对象只会报告玩家 *开始时*的位置：角色带着某人前往某处后停下来等待，玩家走到它身旁，它却一直不动，也没有任何日志说明原因。

### ConvaiActionInvocation 对象

每次 `ExecuteAsync` 调用都会接收一个 `ConvaiActionInvocation` 对象，其中包含执行行为所需的一切信息：

| 属性               | 类型                           | 包含                                                                                                        |
| ---------------- | ---------------------------- | --------------------------------------------------------------------------------------------------------- |
| `Command`        | `ConvaiActionCommand`        | 原始后端命令 — `Name`, `Target`, `HasTarget`                                                                    |
| `Definition`     | `ConvaiActionDefinition`     | 本地定义 — `ActionName`, `TargetRequirement`, `Executor`, `TimeoutSeconds`                                    |
| `ResolvedTarget` | `ConvaiResolvedActionTarget` | 已解析的目标绑定 — `Kind`, `Name`, `ObjectBinding`, `CharacterBinding`, `GameObjectReference`, `InteractionPoint` |
| `Character`      | `ConvaiCharacter`            | 正在执行的 NPC                                                                                                 |
| `BatchIndex`     | `int`                        | 此批次在调度器整个生命周期中的顺序索引                                                                                       |
| `StepIndex`      | `int`                        | 此批次中此步骤的索引（从 0 开始）                                                                                        |

访问目标 `GameObject` ：

```csharp
GameObject targetGo = invocation.ResolvedTarget?.GameObjectReference;
```

对于移动、指向、注视或锚定行为，优先使用 `invocation.ResolvedTarget?.InteractionPoint` 而不是 `GameObjectReference`自身的变换 — 如果为目标设置了显式交互点，则解析为该交互点；否则回退到 `GameObjectReference`的变换。设置交互点的创作者期望每个执行器都遵循它。

不要重新解析 `invocation.Command.Name` 或 `invocation.Command.Target` 来重新推断要执行的操作。请使用 `invocation.Definition` 和 `invocation.ResolvedTarget` — 它们已经解析并通过验证。

### 执行结果类型

从 `ExecuteAsync`:

| 工厂方法                                                                                                               | 适用情况                                                                  |
| ------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------- |
| `ConvaiActionExecutionResult.Succeeded(string message = null)`                                                     | 行为已成功完成，且没有需要告知玩家的内容                                                  |
| `ConvaiActionExecutionResult.Answered(string answer, string message = null)`                                       | 此行为得出了某个结果 — 请参阅 [回答问题，而不是执行操作](#answer-a-question-instead-of-acting) |
| `ConvaiActionExecutionResult.Failed(string message, ConvaiActionFailureReason reason, Exception exception = null)` | 发生了实际错误；建议使用此重载，以便调用方根据结构化原因作出响应                                      |
| `ConvaiActionExecutionResult.Unhandled(string message = null)`                                                     | 此执行器有意不处理此次调用（上下文或目标类型不匹配）                                            |
| `ConvaiActionExecutionResult.Canceled()`                                                                           | 当调度器将未捕获的取消归类为非超时导致时，会自动返回此结果。请勿手动返回此结果 — 应让异常继续传播（见下文“取消”部分）         |

{% hint style="danger" %}
请 **勿** 手动 `ConvaiActionExecutionResult.TimedOut()` 返回。调度器会在 `TimedOut` 自动返回 `TimeoutSeconds` 到期且 `CancellationToken` 被触发时。如果自行返回此结果，结果就会含义不明，而且会绕过调度器的超时跟踪。
{% endhint %}

**`Failed` 与 `Unhandled`:** 当你尝试执行此行为但出现问题时，使用 `Failed` 。当此执行器完全不应处理这次特定调用时，使用 `Unhandled`  — 例如目标类型不匹配。调度器会为 `OnStepFailed` 触发 `Failed` ，并为 `OnStepUnhandled` 触发 `Unhandled`触发；对于 `StopBatch` 失败策略，两者都会被视为未成功。

### 回答问题，而不是执行操作

有些操作会执行可见动作 — 行走、打开、递交。另一些操作则会 *获取信息*：读取仪表、清点群体、测量距离。对于这类操作，玩家所要求的内容就是结果，而且必须将其传达给 Convai Character：

```csharp
// 查询类操作的错误写法：Message 是诊断信息。它会显示在 Console、Actions Editor
// 和你自己的游戏代码中 — 但绝不会传达给角色。玩家听不到任何内容。
return ConvaiActionExecutionResult.Succeeded($"{dial.name} reads {value} kW");

// 正确写法：这句话就是操作的答案，并会告知角色。
return ConvaiActionExecutionResult.Answered($"{dial.name} reads {value} kilowatts.");
```

答案应写成一个通俗的句子，使用第三人称，描述世界中的真实情况，而不是你的代码 —  `"四个箱子中有两个仍未开封。"`，而不是 `"count=2"`。返回答案并不会让角色开口说话；这由该操作的 **完成时机** 设置决定（`ConvaiActionAnswerDelivery`）在 Actions Editor 中，回退到角色的 `ConvaiActionFeedbackRelay`。如果答案设置为除 **告诉玩家** 之外的任何值，它仍会进入角色自身的记忆，因此角色之后可以提及该事实；而且答案无需争抢发言时机：SDK 会暂存答案，直到角色停止说话，而不会将其丢弃。

### 取消

当 `CancellationToken` 在以下情况下触发：

1. `BatchPolicy.ReplaceCurrent` 生效（新批次抢占当前批次）
2. `TimeoutSeconds` 在动作定义中设置的超时时间已到
3. 调度器被禁用或销毁
4. `CancelOnUserSpeech` 在 `ConvaiActionDispatcher` 上启用，且玩家开始说话

在任何循环中或每次 `await`:

```csharp
while (!arrived)
{
    cancellationToken.ThrowIfCancellationRequested();
    // move one step
    await Task.Yield();
}
```

建议让 `OperationCanceledException` 继续向上传播，而不是自行捕获。调度器会将你的 `ExecuteAsync` 包装在 try/catch 中，并对未捕获的 `OperationCanceledException` 异常进行分类：如果该步骤自身的 `TimeoutSeconds` 已到期，则返回 `TimedOut`；对于其他取消情况，则返回 `Canceled`。如果你自行捕获异常并无条件返回 `ConvaiActionExecutionResult.Canceled()`，就会将由超时导致的取消错误报告为 `Canceled` ，而不是 `TimedOut`.

如果需要在取消时执行清理，请使用 `finally` 而不是 `catch` ，这样异常仍会继续传播，从而确保正确分类：

```csharp
try
{
    await SomeAsyncOperation(cancellationToken);
}
finally
{
    // 无论操作成功还是取消，都必须执行的清理工作
}
```

### 完整示例：高亮对象执行器

此执行器会在解析出的目标上启用轮廓效果，等待三秒，然后将其禁用。

```csharp
using System.Threading;
using System.Threading.Tasks;
using Convai.Runtime.Actions;
using UnityEngine;

[AddComponentMenu("MyProject/Actions/Highlight Object Executor")]
public sealed class HighlightObjectExecutor : ConvaiActionExecutorBase
{
    [SerializeField] private float _highlightDuration = 3f;

    public override async Task<ConvaiActionExecutionResult> ExecuteAsync(
        ConvaiActionInvocation invocation,
        CancellationToken cancellationToken)
    {
        // 1. 获取目标
        GameObject targetGo = invocation.ResolvedTarget?.GameObjectReference;
        if (targetGo == null)
            return ConvaiActionExecutionResult.Failed(
                "No target resolved for Highlight action.", ConvaiActionFailureReason.TargetMissing);

        // 2. 查找所需组件
        var outline = targetGo.GetComponent<OutlineEffect>();
        if (outline == null)
            return ConvaiActionExecutionResult.Failed(
                $"Target '{invocation.ResolvedTarget.Name}' has no OutlineEffect component.",
                ConvaiActionFailureReason.PeerMissing);

        // 3. 执行行为
        outline.enabled = true;

        try
        {
            // 4. 等待并响应取消请求
            await Task.Delay(
                (int)(_highlightDuration * 1000),
                cancellationToken);
        }
        finally
        {
            // 无论等待完成还是被取消，都要清理
            if (outline != null)
                outline.enabled = false;
        }

        // 5. 让取消异常从上方的 try 代码块中向外传播，这样
        // 分发器就能正确分类（TimedOut 或 Canceled），而不是由这个
        // 执行器自行判断——请参阅上文的“取消”。
        return ConvaiActionExecutionResult.Succeeded();
    }
}
```

此示例直接继承自 `ConvaiActionExecutorBase` ，以实现完全的手动控制。如果执行器只需要已解析的目标和层级中的同级对象，则可以继承 `ConvaiTargetedActionExecutor` 或 `ConvaiCharacterActionExecutor<TPeer>` 这样就无需执行步骤 1 和 2 中所示的目标空值检查和同级对象查找。

### 复合操作

将整个游戏流程放入一个 `ExecuteAsync`中。分发器会将一个操作定义视为不可分割的整体——它会等待任务完成后才开始下一步。对于拾取、检查、先打开再拿取，或任何包含多个子行为的操作序列，这都是正确的模式。

```csharp
public override async Task<ConvaiActionExecutionResult> ExecuteAsync(
    ConvaiActionInvocation invocation,
    CancellationToken cancellationToken)
{
    // 阶段 1：导航
    ConvaiActionExecutionResult moveResult =
        await _mover.ExecuteAsync(invocation, cancellationToken);
    if (moveResult.Status != ConvaiActionExecutionStatus.Succeeded)
        return moveResult;

    // 阶段 2：交互
    cancellationToken.ThrowIfCancellationRequested();
    _animator.SetTrigger("Interact");

    // 阶段 3：等待动画
    await Task.Delay(1200, cancellationToken);

    // 阶段 4：应用效果
    ApplyInteractionEffect(invocation.ResolvedTarget?.GameObjectReference);

    return ConvaiActionExecutionResult.Succeeded();
}
```

### 执行器设计规则

* **使用 `invocation.ResolvedTarget`，而不是 `invocation.Command.Target`.** 分发器已将名称解析为一个 `GameObject` 绑定——不要重新解析原始字符串。
* **当此执行器不适用时，返回 `Unhandled` 。** 单个执行器组件可以由多个操作定义共享。返回 `Unhandled` 会通知分发器触发 `OnStepUnhandled` 而不会将其视为严重失败。
* **对于查询操作，应返回 `Answered`，而不是 `Succeeded`。** 一条 `Succeeded` 消息永远不会到达 Convai Character；只有 `Answer` 会。
* **在操作定义中设置 `TimeoutSeconds` 。** 请使用超时机制，而不要在执行器中自行实现截止时间逻辑。
* **取消时进行清理。** 如果执行器启用了某种效果、移动了对象或占用了资源，请在 `finally` 代码块中释放它，然后再让取消异常继续传播。
* **不要在多次调用之间保留状态。** 同一个执行器实例可能会在多个批次中针对不同目标被调用。不要假设上一次调用的状态仍然有效。
* **绝不要读取自己的 `transform` 来获取世界空间中的位置或旋转。** 请使用 `CharacterTransform` ——参见 [读取角色的变换，而不是你自己的](#read-the-characters-transform-not-your-own).

### 后续步骤

{% content-ref url="/pages/111bca064ba7041a987662d038af4d71d58a32cd" %}
[配置角色动作](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/character-actions/configuring-actions.md)
{% endcontent-ref %}

{% content-ref url="/pages/0341126fa4c492311dab4fb6aca6d0c64191016b" %}
[角色动作脚本参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/character-actions/actions-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/features/character-actions/writing-custom-executors.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.
