> 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/narrative-design/setting-up-narrative-design-triggers.md).

# 配置叙事设计触发器

介绍如何添加叙事设计触发器，通过碰撞、接近、计时或手动信号推进角色的故事。

`ConvaiNarrativeDesignTrigger` 会向 Convai 发送一个命名信号，使故事图从一个章节推进到下一个章节。将它放在任意 GameObject 上——例如门口、展品或 UI 按钮的事件目标——并选择触发方式。叙事触发器不同于 Unity 物理触发器：激活模式控制的是 *信号* 何时发送，而不是触发哪种 Unity 物理事件。

### 添加触发器组件

{% stepper %}
{% step %}

#### 创建或选择 GameObject

对于基于区域的激活方式（Collision、Proximity、TimeBased），请创建一个空 GameObject，并将其放置在场景中所需的触发区域。对于 Manual 激活方式，可以将组件放置在任意位置。
{% endstep %}

{% step %}

#### 添加组件

点击 **Add Component** 然后导航至 **Convai > Convai Narrative Design Trigger**.

<figure><img src="https://2402152281-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEtUJA212Zc1S9ACc8T4l%2Fuploads%2FM4Gbj8rb6OhxzB28gA98%2Fimage.png?alt=media&amp;token=7b2f3641-98fd-4c2c-804b-9f1e95653e63" alt="ConvaiNarrativeDesignTrigger added via Add Component in the Unity Inspector"><figcaption><p>将 ConvaiNarrativeDesignTrigger 添加到 GameObject。</p></figcaption></figure>
{% endstep %}

{% step %}

#### 指定角色

将你的 `ConvaiCharacter` 拖到 **Character** 字段中。如果留空， **Auto Find Character** 会先搜索父级层级，然后自动搜索 `ConvaiManager`的角色列表。如果场景中有多个角色，请明确指定目标角色。
{% endstep %}

{% step %}

#### 获取并选择触发器

点击 **Fetch** ，位于 **Trigger Selection** 部分中。SDK 会调用 `NarrativeDesignFetcher.FetchTriggersAsync` ，并在下拉菜单中填入仪表板上为此角色定义的所有触发器。

选择此组件要发送的触发器。 **Trigger Name**, **Trigger ID**和 **Destination Section** 字段会自动填充。 **Trigger Message** 仅作为从 Convai 获取的元数据显示；该组件只会发送已保存的触发器名称。

<figure><img src="https://2402152281-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEtUJA212Zc1S9ACc8T4l%2Fuploads%2FEqHSckjPlBbbfdgbpdgE%2Fimage.png?alt=media&amp;token=80be2bb4-5692-467c-bda9-3b63bdbe192c" alt="Trigger Selection dropdown showing fetched triggers from the Convai dashboard"><figcaption><p>从 Convai 仪表板填充的触发器下拉菜单。</p></figcaption></figure>
{% endstep %}

{% step %}

#### 选择激活模式

从下文介绍的四种激活模式中选择一种，并配置其设置。
{% endstep %}
{% endstepper %}

### 激活模式

<figure><img src="https://2402152281-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEtUJA212Zc1S9ACc8T4l%2Fuploads%2FdpxWrkjQHxcgoGSNKgGU%2Fimage.png?alt=media&amp;token=dcaa9022-e321-41d0-8767-667fba499d4a" alt="Activation Settings header in the Inspector showing all four activation mode options"><figcaption><p>带有模式选择器的 Activation Settings 标题。</p></figcaption></figure>

#### Collision

默认模式。当带有标签的玩家 GameObject 进入附加在同一 GameObject 上的碰撞体时，触发器就会触发。

**要求：**

* 同一 GameObject 上的 `Collider` 组件，并且具有 **是触发器** 已启用。
* 触发器 GameObject 或玩家 GameObject 必须至少有一个 `Rigidbody` ，这样 Unity 物理系统才能生成 `OnTriggerEnter` 回调。

{% hint style="warning" %}
如果 **是触发器** 碰撞体未启用此选项，或者触发器对象和玩家都没有 `Rigidbody`, `OnTriggerEnter` 将永远不会触发。启用 **启动时验证** ，即可在场景运行时自动检测此问题。
{% endhint %}

**检测设置：**

| 字段       | 默认值        | 说明                            |
| -------- | ---------- | ----------------------------- |
| **玩家标签** | `"Player"` | 只有带有此标签的 GameObject 才会被识别为玩家。 |
| **玩家层**  | 所有层        | 用于进一步筛选哪些对象可被视为玩家的层遮罩。        |

#### 邻近检测

当玩家与组件的 `Transform` 距离小于 **邻近半径**时，触发器就会触发。每帧都会在 `Update`中进行检测。Scene 视图中会绘制一个绿色球体，以显示检测半径。

| 字段         | 默认值        | 说明                                              |
| ---------- | ---------- | ----------------------------------------------- |
| **邻近半径**   | `3`        | 以世界单位表示的检测半径。                                   |
| **玩家标签**   | `"Player"` | 用于识别玩家的标签。                                      |
| **自动查找玩家** | `true`     | 如果未指定玩家 GameObject，则在场景中搜索带有指定标签的玩家 GameObject。 |

此模式不需要碰撞体。

#### 基于时间

玩家在碰撞体区域内停留达到设定时长后，触发器就会触发。如果玩家在延迟结束前离开，倒计时会取消；玩家下次进入时，倒计时将重新开始。

**要求：** 与碰撞模式相同的碰撞体设置。

| 字段       | 默认值        | 说明                    |
| -------- | ---------- | --------------------- |
| **时间延迟** | `0`        | 触发器触发前，玩家必须在区域内停留的秒数。 |
| **玩家标签** | `"Player"` | 用于识别玩家的标签。            |

#### 手动

触发器不会自动执行任何操作。通过你自己的代码或 Unity 事件调用 `InvokeTrigger()` 或 `TryInvokeTrigger()` 即可触发它。当激活条件完全由游戏逻辑控制时，请使用此模式，例如 UI 按钮、任务完成回调，或计分交互。

```csharp
// 从代码触发触发器
narrativeTrigger.InvokeTrigger();

// 静默尝试 — 如果 TriggerOnce 已触发，则跳过且不发出警告
narrativeTrigger.TryInvokeTrigger();
```

### 触发请求模式

激活模式和触发请求模式是两个独立的设置。激活模式（`Collision`, `Proximity`, `TimeBased`, `Manual`）控制 *何时* `ConvaiNarrativeDesignTrigger` 触发，如上所述。触发请求模式则控制触发后通过 RTVI 发送给 Convai 的 *内容* 。

`ConvaiNarrativeDesignTrigger` 始终使用 `ConvaiNarrativeTriggerMode.SavedTrigger`发送已配置的触发器。在内部，它会调用 `convaiCharacter.NarrativeDesign.InvokeTrigger(_triggerName)`，仅发送 `trigger_name` 字段。此组件没有可在 Inspector 中切换到其他两种触发请求模式的选项。

此外， `ConvaiNarrativeTriggerRequest` （命名空间 `Convai.Runtime.NarrativeDesign`):

| 触发请求模式           | 连接字段                                 | 发送方式                                                                                          |
| ---------------- | ------------------------------------ | --------------------------------------------------------------------------------------------- |
| `SavedTrigger`   | `trigger_name`                       | `ConvaiNarrativeDesignTrigger` （此组件），或通过代码调用 `IConvaiNarrativeDesign.InvokeTrigger(string)` 。 |
| `InlineEvent`    | `trigger_message`                    | `IConvaiNarrativeDesign.InvokeEvent(string)` — 只能通过代码调用，Inspector 中没有对应选项                     |
| `ScriptedSpeech` | `trigger_message` （用 `<speak>` 标签包裹） | `IConvaiNarrativeDesign.InvokeSpeech(string)` — 只能通过代码调用，Inspector 中没有对应选项                    |

`InlineEvent` 和 `ScriptedSpeech` 无法通过此组件的 Inspector 使用。使用 `InvokeEvent` 发送上下文事件文本，让 Convai 自然地作出回应；或者使用 `InvokeSpeech` 让角色准确说出预先编写的文本，而不推进叙事图。请参阅 [叙事设计脚本参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/narrative-design/scripting-narrative-design.md) ，了解完整代码 API。

### 自动恢复设置

这些设置可让触发器适应常见的运行时状况，例如角色或玩家可能无法立即就绪。

<figure><img src="https://2402152281-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEtUJA212Zc1S9ACc8T4l%2Fuploads%2F32eKYsxh76KaDYTQLAsv%2Fimage.png?alt=media&amp;token=ad906023-378b-4118-9cc6-c07509d52f94" alt="Auto-Recovery Settings header in the Inspector"><figcaption><p>“自动恢复设置”标题。</p></figcaption></figure>

| 字段          | 默认值    | 说明                                                                                                                  |
| ----------- | ------ | ------------------------------------------------------------------------------------------------------------------- |
| **自动查找角色**  | `true` | 搜索父级层级，然后搜索 `ConvaiManager.Characters`。如果只存在一个角色，则自动分配；如果找到多个角色，则记录警告。                                              |
| **自动查找玩家**  | `true` | 先按玩家标签搜索，再按常见名称列表搜索，最后通过 `Camera.main.parent`.                                                                      |
| **就绪前排队**   | `true` | 如果角色尚未处于活跃对话中（`IsInConversation` 为 `false`），触发器会进入队列，并在连接建立后自动触发。调用 `IsInConversation` 之前，无需手动检查 `InvokeTrigger()`. |
| **最长等待时间**  | `30`   | 等待角色就绪的最长秒数。设为 `0` 表示不设超时。                                                                                          |
| **场景加载时重置** | `true` | 每当加载场景时调用 `ResetTrigger()` ，使触发器可以在重新加载的场景中再次触发。                                                                    |

{% hint style="warning" %}
将 **最长等待时间** 设为 `0` ，在会话可能永远无法连接的生产版本中会创建一个无限期运行的协程。除非你能明确控制会话的生命周期，否则请务必设置合理的超时时间。
{% endhint %}

### 控制触发频率

**仅触发一次** （默认值为 `true`）可防止触发器触发多次。首次成功调用后， `HasTriggered` 将变为 `true`, `CurrentStatus` 将变为 `AlreadyFired`，之后的所有调用都会返回 `false`.

若要允许触发器再次触发，请调用 `ResetTrigger()`:

```csharp
narrativeTrigger.ResetTrigger();
```

`ResetTrigger()` 还会取消任何正在等待角色就绪的排队触发器。

若要让触发器在每次激活时都触发，请在检查器中停用 **仅触发一次** 。

### 事件参考

| 事件                   | 签名                   | 触发时机                        |
| -------------------- | -------------------- | --------------------------- |
| `OnTriggerActivated` | `UnityEvent`         | 触发器已成功发送到后端。                |
| `OnPlayerEnterZone`  | `UnityEvent`         | 玩家进入碰撞体或邻近区域时（触发器触发之前）。     |
| `OnPlayerExitZone`   | `UnityEvent`         | 玩家离开碰撞体或邻近区域时。              |
| `OnTriggerFailed`    | `UnityEvent<string>` | 触发器无法触发。字符串参数包含错误消息。        |
| `OnTriggerQueued`    | `UnityEvent`         | 触发器已接受，但由于角色尚未进入对话，因此被延后处理。 |

### 触发器状态

该 `CurrentStatus` 属性始终跟踪触发器的状态：

```mermaid
stateDiagram-v2
    [*] --> Ready
    Ready --> AlreadyFired : InvokeTrigger() succeeds\n(TriggerOnce = true)
    Ready --> QueuedWaitingForCharacter : InvokeTrigger() called\ncharacter not ready\nQueueUntilReady = true
    Ready --> 配置错误：ValidateConfiguration() 失败
    QueuedWaitingForCharacter --> AlreadyFired：角色变为就绪状态
    QueuedWaitingForCharacter --> ConfigurationError：MaxWaitTime 超时
    AlreadyFired --> Ready：ResetTrigger()
    ConfigurationError --> Ready：修复问题 + ValidateConfiguration()
    Ready --> Disabled：组件或 GameObject 已禁用
    Disabled --> Ready：组件或 GameObject 已重新启用
```

请参阅 [叙事设计故障排除](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/narrative-design/troubleshooting-and-diagnostics.md) ，了解每种状态的完整解决指南。

### 检查器引用

#### Character Reference 标题

| 字段         | 默认值    | 说明                                              |
| ---------- | ------ | ----------------------------------------------- |
| **角色**     | 无      | 目标 `ConvaiCharacter`. 为空时自动查找，且 **自动查找角色** 已启用。 |
| **自动查找角色** | `true` | 当 Character 字段为空时，在层级结构和 ConvaiManager 中搜索。     |

#### 触发器选择标题

| 字段         | 默认值 | 说明                                                     |
| ---------- | --- | ------------------------------------------------------ |
| **触发器 ID** | 空   | 选择后为只读。来自控制面板的唯一标识符。                                   |
| **触发器名称**  | 空   | 保存的触发器名称，此组件触发时会发送给 Convai。                            |
| **触发器消息**  | 空   | 从 Convai 获取的只读元数据。它不会由 `ConvaiNarrativeDesignTrigger`. |

#### 激活设置标题

| 字段        | 默认值        | 说明                                   |
| --------- | ---------- | ------------------------------------ |
| **激活模式**  | `碰撞`       | 触发器的激活方式： `碰撞`, `接近`, `手动`，或 `基于时间`. |
| **邻近半径**  | `3`        | 接近模式下的检测半径。                          |
| **时间延迟**  | `0`        | 基于时间模式的倒计时秒数。                        |
| **仅触发一次** | `true`     | 启用后，仅触发一次，直到调用 `ResetTrigger()` 为止。  |
| **玩家层**   | 全部         | 用于检测玩家的图层遮罩。                         |
| **玩家标签**  | `"Player"` | 用于识别玩家 GameObject 的标签。               |

#### 自动恢复设置标题

| 字段          | 默认值    | 说明                         |
| ----------- | ------ | -------------------------- |
| **自动查找玩家**  | `true` | 如果未检测到玩家，则在场景中搜索带有指定标签的玩家。 |
| **就绪前排队**   | `true` | 将触发操作延迟到角色会话开启后执行。         |
| **最长等待时间**  | `30`   | 队列的超时时间（秒）。 `0` = 无超时。     |
| **场景加载时重置** | `true` | 在场景加载时重置 `HasTriggered` 。  |

#### 诊断标题

| 字段        | 默认值     | 说明                                           |
| --------- | ------- | -------------------------------------------- |
| **启用诊断**  | `false` | 将详细的状态转换记录到控制台。                              |
| **启动时验证** | `true`  | 在启动时运行 `ValidateConfiguration()` 并记录发现的任何问题。 |

### 后续步骤

{% content-ref url="/pages/630c1743293b81e62f2237b571dcf928c0d73285" %}
[配置叙事模板键](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/narrative-design/template-keys-dynamic-narrative-variables.md)
{% endcontent-ref %}

{% content-ref url="/pages/e2aeb655628e9664d3a8c2993eb219a88fcfeef0" %}
[叙事设计脚本参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/narrative-design/scripting-narrative-design.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/narrative-design/setting-up-narrative-design-triggers.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.
