> 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/narrative-design/scripting-narrative-design.md). Agents can also search and read this documentation through its [MCP server](https://docs.convai.com/api-docs/~gitbook/mcp).

# 脚本化叙事设计

Narrative Design 的完整 C# 接口——IConvaiNarrativeDesign 事件、InvokeTrigger、带 speak 标签的 InvokeSpeech、异步章节获取以及运行时触发器重新配置。

## 以编程方式控制叙事设计

Inspector 工作流涵盖了大多数使用场景。本页介绍完整的 C# 接口，适用于需要以编程方式进行控制的情况，例如动态切换角色、在运行时异步获取数据、生成运行时叙事流程，或与自有游戏系统深度集成。

此处介绍的所有功能均可通过 `IConvaiNarrativeDesign`访问；每个 `ConvaiCharacter` 都通过 `NarrativeDesign` 属性公开该接口。 `ConvaiNarrativeDesignManager` 和 `ConvaiNarrativeDesignTrigger` 在内部都委托给此接口，因此你在 Inspector 中配置的所有内容也都可以通过代码访问。

## 访问角色 API

每个 `ConvaiCharacter` 都公开一个 `NarrativeDesign` 属性，该属性返回一个 `IConvaiNarrativeDesign` 实现：

```csharp
ConvaiCharacter character = GetComponent<ConvaiCharacter>();
IConvaiNarrativeDesign narrative = character.NarrativeDesign;
```

### 属性

| 属性                   | 类型                                    | 说明                                                                                         |
| -------------------- | ------------------------------------- | ------------------------------------------------------------------------------------------ |
| `TemplateKeys`       | `IReadOnlyDictionary<string, string>` | 当前为此角色跟踪的所有模板键的快照。                                                                         |
| `CurrentSectionId`   | `string`                              | 最近从后端收到的分区 ID。如果尚未收到任何分区，则为空字符串。                                                           |
| `CurrentSectionData` | `NarrativeSectionData`                | 完整的分区负载，包含 `SectionId`, `BehaviorTreeCode`和 `BehaviorTreeConstants`. `null` ，直到收到首次分区变更为止。 |

## 监听分区变更

在 `OnEnable` 中订阅这些事件，并在 `OnDisable` 中取消订阅，以避免组件被禁用或销毁后留下过期的监听器。

```csharp
private void OnEnable()
{
    character.NarrativeDesign.OnSectionChanged     += HandleSectionChanged;
    character.NarrativeDesign.OnSectionDataReceived += HandleSectionData;
}

private void OnDisable()
{
    character.NarrativeDesign.OnSectionChanged     -= HandleSectionChanged;
    character.NarrativeDesign.OnSectionDataReceived -= HandleSectionData;
}

private void HandleSectionChanged(string previousId, string newId)
{
    Debug.Log($"Section: {previousId} → {newId}");
}

private void HandleSectionData(NarrativeSectionData data)
{
    Debug.Log($"Section ID: {data.SectionId}");
    // data.BehaviorTreeCode and data.BehaviorTreeConstants available here
}
```

### 事件

| 事件                      | 签名                                         | 说明                                   |
| ----------------------- | ------------------------------------------ | ------------------------------------ |
| `OnSectionChanged`      | `Action<string, string>`                   | 每次分区转换时触发。参数： `previousId`, `newId`. |
| `OnSectionDataReceived` | `Action<NarrativeSectionData>`             | 每次分区转换时触发，并携带完整数据。                   |
| `OnTriggerInvoked`      | `Action<ConvaiNarrativeTriggerInvocation>` | 触发器或语音请求在本地被接受后触发（后端确认之前）。           |

{% hint style="warning" %}
`OnSectionChanged` 和 `OnSectionDataReceived` 通过 SDK 的内部 `EventHub`传递。如果订阅回调中运行的代码会调用 Unity API（例如， `GameObject.SetActive`），请确保场景中存在 `ConvaiNarrativeDesignManager` ——它会自动在主线程上传递事件。直接订阅 `IConvaiNarrativeDesign` 事件时，事件可能会根据配置在后台线程上触发。
{% endhint %}

## 通过代码调用触发器

```csharp
// 命名触发器——使图沿特定边推进
bool accepted = character.NarrativeDesign.InvokeTrigger("CheckpointReached");

// 带有可选消息负载的命名触发器
character.NarrativeDesign.InvokeTrigger("ItemInspected", "The fire extinguisher is missing its pin.");
```

`InvokeTrigger` 返回 `false` 如果 `triggerName` 和 `triggerMessage` 均为空，或者触发器在内部被拒绝。否则，它会返回 `true` ；如果会话尚未开启，则会将触发器加入队列。

## 控制角色说什么

`InvokeSpeech` 可让你直接控制角色接下来要说的话，而不会推进叙事图。根据消息是否使用 `<speak>` 标签包裹，它有两种不同模式。

### 注入上下文（纯文本）

传入一个纯文本字符串，让角色 *了解到* 某条信息。角色会吸收这段上下文，并用自己的话作出回应——具体措辞由 AI 决定。

```csharp
// 角色会了解到这一事实，并自然地作出回应
character.NarrativeDesign.InvokeSpeech("The trainee just completed the evacuation drill.");
```

当你希望角色以自然、对话式的方式回应游戏事件，而不是照稿宣读时，请使用此模式。

### 逐字朗读（speak 标签）

将消息包裹在 `<speak>` 标签中，让角色逐字说出该文本。

```csharp
// 角色逐字说出此句
character.NarrativeDesign.InvokeSpeech("<speak>Attention: the fire exit on level two is now unlocked.</speak>");
```

用于公告、脚本台词、安全警报，或任何措辞必须完全准确的场景。

### 比较

| 模式                                    | 角色的行为          |
| ------------------------------------- | -------------- |
| `InvokeSpeech("text")`                | 感知上下文，并用自己的话回应 |
| `InvokeSpeech("<speak>text</speak>")` | 逐字说出该文本        |

{% hint style="info" %}
`InvokeSpeech` 无论使用哪种模式，都不会推进叙事图。若要在发送消息的同时推进叙事图，请使用 `InvokeTrigger` 并指定一个命名触发器。
{% endhint %}

### 监听触发器调用

```csharp
character.NarrativeDesign.OnTriggerInvoked += invocation =>
{
    Debug.Log($"Trigger: {invocation.TriggerName}, Queued: {invocation.Queued}");
};
```

`ConvaiNarrativeTriggerInvocation` 字段：

| 字段               | 类型       | 说明                                 |
| ---------------- | -------- | ---------------------------------- |
| `TriggerName`    | `string` | 已发送的触发器名称（语音消息时为空）。                |
| `TriggerMessage` | `string` | 可选的消息负载。                           |
| `Queued`         | `bool`   | `true` 如果因会话尚未开启而延迟了触发器，则此值为 true。 |

## 通过代码设置模板键

```csharp
// 设置单个键
character.NarrativeDesign.SetTemplateKey("PlayerName", "Alex");

// 设置多个键
character.NarrativeDesign.SetTemplateKeys(new Dictionary<string, string>
{
    { "PlayerName",  "Alex" },
    { "ScoreLevel",  "Intermediate" }
});
```

如果会话已开启，这两种方法都会立即发送；否则会将内容排队，等待下次连接时发送。

角色级 API 和 `ConvaiNarrativeDesignManager`的方法在内部最终使用同一传输机制。若希望在 Inspector 中查看和编辑这些键，请使用 Manager 的方法；若工作流完全由代码驱动且无需在 Inspector 中查看，则使用角色 API。

## 以编程方式获取章节和触发器

### 通过角色 API

```csharp
NarrativeFetchResult<List<NarrativeSectionInfo>> result =
    await character.NarrativeDesign.FetchSectionsAsync();

if (result.Success)
{
    foreach (NarrativeSectionInfo section in result.Data)
        Debug.Log($"{section.SectionId}: {section.SectionName}");
}
else
{
    Debug.LogError(result.Error);
}
```

```csharp
NarrativeFetchResult<List<NarrativeTriggerInfo>> result =
    await character.NarrativeDesign.FetchTriggersAsync();

foreach (NarrativeTriggerInfo trigger in result.Data)
    Debug.Log($"{trigger.TriggerName} → {trigger.DestinationSection}");
```

`NarrativeSectionInfo` 字段： `SectionId`, `SectionName`.

`NarrativeTriggerInfo` 字段： `TriggerId`, `TriggerName`, `TriggerMessage`, `DestinationSection`.

### 通过静态获取器

`NarrativeDesignFetcher` 无需引用角色组件即可获取相同的数据——适用于编辑器工具或加载界面：

```csharp
// 获取章节
FetchResult<List<SectionData>> sections =
    await NarrativeDesignFetcher.FetchSectionsAsync(characterId);

// 获取触发器
FetchResult<List<TriggerData>> triggers =
    await NarrativeDesignFetcher.FetchTriggersAsync(characterId);

// 并行获取两者
var (sectionsResult, triggersResult) =
    await NarrativeDesignFetcher.FetchAllAsync(characterId);
```

`FetchResult<T>` 字段：

| 字段        | 类型       | 说明                                       |
| --------- | -------- | ---------------------------------------- |
| `Success` | `bool`   | `true` 如果请求成功。                           |
| `Data`    | `T`      | 获取到的数据。 `default` 当 `Success` 为 `false`. |
| `Error`   | `string` | 错误消息。 `null` 当 `Success` 为 `true`.       |

## 重置状态

```csharp
// 仅重置控制器状态（清除 CurrentSectionID 和 CurrentSectionData）
// 不会影响章节配置列表或 Unity 事件的连接
narrativeManager.ResetController();

// 永久清除所有章节配置（移除所有 UnitySectionEventConfig 条目）
// 仅在切换到完全不同的角色时使用
narrativeManager.ClearAllSectionConfigs();
```

{% hint style="warning" %}
`ClearAllSectionConfigs()` 会移除所有 `UnitySectionEventConfig` 条目以及所有 Unity Event 绑定。此操作在运行时无法撤销。只有在确认要切换到其他角色且不再需要现有分区事件绑定时，才调用此方法。
{% endhint %}

## 通过代码重新配置 ConvaiNarrativeDesignTrigger

所有可在 Inspector 中配置的设置都有对应的 setter 方法：

```csharp
ConvaiNarrativeDesignTrigger trigger = GetComponent<ConvaiNarrativeDesignTrigger>();

// 覆盖触发器选择
trigger.SetTrigger("trigger-uuid", "CheckpointA", "Player reached checkpoint A");

// 在运行时更改激活模式
trigger.SetActivationMode(TriggerActivationMode.Proximity);
trigger.SetProximityRadius(5f);

// 指定已知的玩家 Transform（自动查找无法满足需求时很有用）
trigger.SetPlayerTransform(playerController.transform);

// 切换目标角色
trigger.SetCharacter(otherCharacter.GetComponent<IConvaiCharacterAgent>());

// 在关键触发器执行前进行验证
if (!trigger.ValidateConfiguration())
{
    foreach (string warning in trigger.ValidationWarnings)
        Debug.LogWarning(warning);
}
```

## 架构概览

```mermaid
classDiagram
    class ConvaiNarrativeDesignManager {
        +UpdateTemplateKey(key, value)
        +FetchAndSyncFromBackend()
        +OnAnySectionChanged UnityEvent
    }
    class ConvaiNarrativeDesignTrigger {
        +InvokeTrigger() bool
        +ResetTrigger()
        +ValidateConfiguration() bool
    }
    class IConvaiNarrativeDesign {
        +SetTemplateKey(key, value) bool
        +InvokeTrigger(name, msg) bool
        +InvokeSpeech(msg) bool
        +FetchSectionsAsync() Task
        +OnSectionChanged Action
    }
    class CharacterNarrativeDesignFacade {
        -_templateKeys Dictionary
        -_pendingTriggers Queue
        +FlushPending()
    }
    class ConnectionService {
        +UpdateTemplateKeys(keys)
        +SendTrigger(name, msg)
    }

    ConvaiNarrativeDesignManager ..> IConvaiNarrativeDesign : 委托给
    ConvaiNarrativeDesignTrigger ..> IConvaiNarrativeDesign : 调用 InvokeTrigger
    IConvaiNarrativeDesign <|.. CharacterNarrativeDesignFacade
    CharacterNarrativeDesignFacade --> ConnectionService : 通过 RTVI 发送
```

## 总结

`IConvaiNarrativeDesign` 通过代码提供完整的叙事设计功能，包括触发器调用、语音注入、模板键控制、异步数据获取以及实时分区变更事件。借助它，你可以将这些功能集成到任何架构中，而不受 Inspector 组件的限制。如需查看将这些 API 组合应用于实际场景的完整示例，请参阅 [使用示例](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/unity-plugin-beta-overview/features/narrative-design/usage-examples.md)。有关问题诊断，请参阅“故障排除与诊断”。


---

# 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/narrative-design/scripting-narrative-design.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.
