> 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/unity-plugin-beta-overview/features/actions/writing-custom-executors.md). Agents can also search and read this documentation through its [MCP server](https://docs.convai.com/api-docs/~gitbook/mcp).

# 编写自定义执行器

实现 IConvaiActionExecutor，以创建项目所需的任何行为——包含完整示例、取消处理和复合动作模式。

## 何时编写自定义执行器

Convai SDK 附带的执行器涵盖了常见场景，但每个项目都有独特的行为需求。在以下情况下，请编写自定义执行器：

* 游戏使用自定义移动系统（角色控制器、物理系统或寻路库）
* 需要与 UI 系统、背包、物理对象或外部服务交互
* 希望通过条件逻辑组合多种行为
* 内置执行器无法满足 NPC 所需的精确行为

自定义执行器本质上只是 **C# 类** ——一个实现了某个接口的 MonoBehaviour。除此之外，没有 SDK 特有的样板代码。

***

## IConvaiActionExecutor 接口

任何实现了 `IConvaiActionExecutor` 的 MonoBehaviour 都可以用作执行器。

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

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

该方法被设计为 `async` 。你可以在其中 `await` 协程、任务或任何异步操作。

***

## 调用对象

`ConvaiActionInvocation` 会传递给 `ExecuteAsync` ，其中包含运行该行为所需的一切信息：

| 属性               | 类型                           | 说明                                                                 |
| ---------------- | ---------------------------- | ------------------------------------------------------------------ |
| `Command`        | `ConvaiActionCommand`        | 来自后端的原始命令： `Command.Name` 和 `Command.Target` （尚未解析的目标名称字符串）。       |
| `Definition`     | `ConvaiActionDefinition`     | 本地动作定义： `Definition.ActionName`, `Definition.TimeoutSeconds`等。     |
| `ResolvedTarget` | `ConvaiResolvedActionTarget` | 匹配到的目标。 `ResolvedTarget.GameObjectReference` 可让你获取场景中的 GameObject。 |
| `Character`      | `ConvaiCharacter`            | 执行此动作的角色。                                                          |
| `BatchIndex`     | int                          | 此调用所属的批次（从 0 开始）。                                                  |
| `StepIndex`      | int                          | 此步骤在批次中的索引（从 0 开始）。                                                |

要获取目标在场景中的 GameObject：

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

***

## 返回结果

从以下工厂方法中返回一个 `ConvaiActionExecutionResult`:

| 方法                                                                 | 使用时机                                                          |
| ------------------------------------------------------------------ | ------------------------------------------------------------- |
| `ConvaiActionExecutionResult.Succeeded()`                          | 操作已成功完成。                                                      |
| `ConvaiActionExecutionResult.Failed(string message, Exception ex)` | 发生了问题（缺少组件、状态无效等）。消息和异常均为可选项。                                 |
| `ConvaiActionExecutionResult.Unhandled(string message)`            | 此执行器无法处理给定的调用（例如，目标类型错误）。分发器会触发 `OnStepUnhandled`。消息为可选项。     |
| `ConvaiActionExecutionResult.Canceled()`                           | 操作已取消（通常是因为你检测到 `cancellationToken.IsCancellationRequested`). |
| `ConvaiActionExecutionResult.TimedOut()`                           | 当 `TimeoutSeconds` 超时后，分发器会自动返回此结果——你无需手动返回。                  |

***

## 取消与超时

`ExecuteAsync` 会接收一个 `CancellationToken`。以下情况会取消此令牌：

* 批次被取消（例如， `ReplaceCurrent` 策略收到一个新批次）
* 操作的 `TimeoutSeconds` 到期

如果执行器运行循环或等待长时间运行的操作， **请检查令牌** 以避免无限期阻塞：

```csharp
while (!arrived)
{
    if (cancellationToken.IsCancellationRequested)
        return ConvaiActionExecutionResult.Canceled();

    await Task.Yield();
}
```

或者直接将令牌用于 `await` ——分发器会自动捕获 `OperationCanceledException` ：

```csharp
await Task.Delay(500, cancellationToken); // Throws if canceled
```

***

## 分步操作：构建“高亮对象”执行器

此示例将构建一个 `HighlightObjectExecutor` 触发时，它会启用目标对象上的轮廓/高亮组件，等待三秒，然后将其禁用。

{% stepper %}
{% step %}
**创建脚本**

新建一个 C# 文件，命名为 `HighlightObjectExecutor.cs` 在你的项目中：

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

[AddComponentMenu("My Game/Highlight Object Executor")]
public sealed class HighlightObjectExecutor : MonoBehaviour, IConvaiActionExecutor
{
    [SerializeField] private float _highlightDuration = 3f;

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

        // 2. 在目标上查找高亮组件
        Outline outline = targetGo.GetComponent<Outline>();
        if (outline == null)
            return ConvaiActionExecutionResult.Failed($"No Outline component found on '{targetGo.name}'.");

        // 3. 启用高亮
        outline.enabled = true;

        // 4. 等待高亮持续时间（支持取消）
        try
        {
            await Task.Delay(
                (int)(_highlightDuration * 1000),
                cancellationToken);
        }
        catch (TaskCanceledException)
        {
            outline.enabled = false;
            return ConvaiActionExecutionResult.Canceled();
        }

        // 5. 关闭高亮并返回成功
        outline.enabled = false;
        return ConvaiActionExecutionResult.Succeeded();
    }
}
```

{% endstep %}

{% step %}
**将组件添加到你的 NPC**

选中 NPC 的 GameObject，然后点击 **添加组件 → 我的游戏 → Highlight Object Executor**.

将 **高亮持续时间** 设为所需值（默认值：3 秒）。
{% endstep %}

{% step %}
**将其关联到操作定义**

在 `ConvaiActionConfigSource` （位于同一个 NPC GameObject 上）中：

1. 在 **操作定义**.
2. 中添加一个新条目 **操作名称** 设为 `Highlight` （或你使用的其他名称）。
3. 将 **目标要求** 设为 `Object`.
4. 将 `HighlightObjectExecutor` 拖到 **执行器** 字段中。
   {% endstep %}

{% step %}
**测试**

按下 **播放** 并对角色说：

> *“标出灭火器。”*

灭火器上的 Outline 组件应启用三秒，然后禁用。
{% endstep %}
{% endstepper %}

***

## 一个更简单的示例：传送执行器

供参考，下面是最简自定义执行器模式——不进行异步等待，只执行同步操作：

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

public sealed class TeleportToTargetExecutor : MonoBehaviour, IConvaiActionExecutor
{
    [SerializeField] private Transform _moveRoot;

    public Task<ConvaiActionExecutionResult> ExecuteAsync(
        ConvaiActionInvocation invocation,
        CancellationToken cancellationToken)
    {
        GameObject targetGo = invocation.ResolvedTarget?.GameObjectReference;
        if (targetGo == null)
            return Task.FromResult(ConvaiActionExecutionResult.Failed("No target resolved."));

        Transform root = _moveRoot != null ? _moveRoot : transform;
        root.position = targetGo.transform.position;

        return Task.FromResult(ConvaiActionExecutionResult.Succeeded());
    }
}
```

请注意这里使用了 `Task.FromResult` ——对于同步执行器，应封装结果，而不是使用 `async`/`await`.

***

## 复合执行器模式

对于由多个游戏步骤组成的操作，请将整个序列放在一个 `ExecuteAsync`中。调度器会将一个操作定义视为不可分割的整体——它会等待任务完成后再开始下一步。

```csharp
public async Task<ConvaiActionExecutionResult> ExecuteAsync(
    ConvaiActionInvocation invocation,
    CancellationToken cancellationToken)
{
    // 步骤 1：移动到目标位置
    ConvaiActionExecutionResult moveResult =
        await _mover.ExecuteAsync(invocation, cancellationToken);
    if (moveResult.Status != ConvaiActionExecutionStatus.Succeeded)
        return moveResult; // 传播失败结果——不要继续

    // 步骤 2：播放动画
    if (_animator != null)
        _animator.SetTrigger(_triggerName);

    // 步骤 3：等待动画结束（支持取消）
    await Task.Delay(TimeSpan.FromSeconds(_animationDuration), cancellationToken);

    // 步骤 4：将物体附加到角色的手上
    if (_attachPoint != null)
    {
        Transform targetTransform = invocation.ResolvedTarget.GameObjectReference.transform;
        targetTransform.SetParent(_attachPoint, worldPositionStays: false);
        targetTransform.localPosition = Vector3.zero;
        targetTransform.localRotation = Quaternion.identity;
    }

    return ConvaiActionExecutionResult.Succeeded();
}
```

{% hint style="info" %}
请参阅 SDK 中的 `PickUpActionExecutor` ，了解此模式的完整参考实现。
{% endhint %}

***

## 提示和最佳实践

{% hint style="info" %}
**当此执行器不适合处理当前任务时，返回 `Unhandled` 。** 例如，如果某个执行器只处理生物目标，却收到一个物体目标，则返回 `Unhandled` 而不是 `Failed`。这样，其他执行器（或回退机制）就可以处理该步骤，而不会将其计为失败。
{% endhint %}

{% hint style="info" %}
**返回 `Failed` 用于真正的错误** ——例如缺少组件、空引用或状态无效。请添加描述性消息，以便调试探针和控制台日志帮助你排查问题。
{% endhint %}

{% hint style="warning" %}
**在任何循环或较长时间的 await 操作中，都要检查 CancellationToken。** 在 `ExecuteAsync` 中，如果循环未检查取消状态，就会阻塞调度器，导致无法运行新批次，即使策略已取消当前批次也是如此。
{% endhint %}

{% hint style="info" %}
**执行器在 Unity 主线程上运行。** 你可以安全地访问 `transform`, `GetComponent`, `Instantiate`以及其他 Unity API，无需进行线程切换。
{% endhint %}

{% hint style="warning" %}
**请使用 `invocation.ResolvedTarget` 和 `invocation.Definition` ——不要重新解析 `invocation.Command.Name` 或 `Command.Target` 。** 目标解析和规范化工作已经为你完成。自行解析原始字符串会绕过不区分大小写的匹配，导致代码脆弱易错。
{% endhint %}

{% hint style="info" %}
**只要游戏逻辑仍在运行，就要让任务保持活动状态。** 调度器会等待 `ExecuteAsync` 返回后才开始下一步。对于寻路等长时间运行的操作，应让执行器中的循环持续运行，直到工作实际完成。
{% endhint %}

***

## 总结

自定义执行器只是一个包含单个方法的 MonoBehaviour。实现 `IConvaiActionExecutor`，从 `invocation.ResolvedTarget.GameObjectReference`获取目标，执行所需操作，然后返回结果。对于长时间运行的行为，请使用 `async`/`await` 并检查 `CancellationToken` ，以遵循超时和策略取消。


---

# 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/unity-plugin-beta-overview/features/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.
