> 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/usage-examples.md).

# 叙事设计使用示例

四个完整的 Narrative Design 示例，从单触发欢迎序列到带动态反馈的自适应多区段场景。

以下示例展示了如何组合 `ConvaiNarrativeDesignManager`, `ConvaiNarrativeDesignTrigger`和 `IConvaiNarrativeDesign` ，构建完整且可正常运行的设置。这些示例按从简单到高级的顺序排列，涵盖不同领域，以展示叙事设计支持的广度。每个示例都可独立使用——请从符合当前复杂度需求的示例开始。

### 示例 1：脚本化欢迎流程

**复杂度：** 入门 | **激活模式：** 手动 | **使用的功能：** 管理器、触发器（手动）、一个模板键

**场景：** 访客来到接待台。UI 中的“开始”按钮通过发送单个触发器启动体验，使角色从空闲状态进入正在进行的欢迎环节。

#### 设置

{% stepper %}
{% step %}

#### 准备场景

将 `ConvaiNarrativeDesignManager` 添加到角色 GameObject，并从控制面板同步各个环节。至少需要两个环节：一个空闲环节（角色在此等待）和一个欢迎环节（角色从此处开始体验）。
{% endstep %}

{% step %}

#### 在会话开始前设置访客姓名

在开始会话之前，发送一个模板键，以便角色能用姓名称呼访客：

```csharp
public class ReceptionController : MonoBehaviour
{
    [SerializeField] private ConvaiNarrativeDesignManager _narrativeManager;
    [SerializeField] private string _visitorName;

    private void Start()
    {
        _narrativeManager.UpdateAndSendTemplateKey("VisitorName", _visitorName);
    }
}
```

{% endstep %}

{% step %}

#### 添加手动触发器

将 `ConvaiNarrativeDesignTrigger` 添加到任意 GameObject（它不会出现在场景中——而是由 UI 驱动）。将 **激活模式** 设为 **手动** 并从控制面板获取/选择欢迎触发器。
{% endstep %}

{% step %}

#### 连接 UI 按钮

在 Button 组件的 **On Click ()** 事件中，指定 `ConvaiNarrativeDesignTrigger` 并选择 `ConvaiNarrativeDesignTrigger.InvokeTrigger`.
{% endstep %}

{% step %}

#### 连接环节事件

在管理器的 **叙事环节** 列表中，找到欢迎环节条目并添加一个 `OnSectionStart` 侦听器。将其指向欢迎环节开始时需要在场景中发生变化的对象——例如，启用姓名徽章 UI 或启动环境动画。
{% endstep %}
{% endstepper %}

**运行时会发生什么：** 玩家点击“开始” → `InvokeTrigger()` 将触发器发送到后端 → 图谱切换到欢迎环节 → `OnSectionStart` 在进入欢迎部分时触发 → 角色开始欢迎语。

### 示例 2：分支对话

**复杂度：** 中级 | **激活模式：** 手动（由代码驱动） | **使用的功能：** Manager、 `IConvaiNarrativeDesign`, `InvokeSpeech`、多个模板键

**场景：** 一位入职引导助手可以引导用户了解三个互不相关的主题领域（设施、系统访问权限、规章制度）。用户通过 UI 按钮选择主题，也可以在主题之间自由切换。每个主题结束后，都支持用户提出开放式的后续问题。

#### 设置

在 Manager 中同步所有主题部分。不需要 `ConvaiNarrativeDesignTrigger` 组件——直接通过 `IConvaiNarrativeDesign`.

```csharp
public class OrientationController : MonoBehaviour
{
    [SerializeField] private ConvaiCharacter _character;
    [SerializeField] private ConvaiNarrativeDesignManager _narrativeManager;
    [SerializeField] private TextMeshProUGUI _activeTopicLabel;

    private void OnEnable()
    {
        _character.NarrativeDesign.OnSectionChanged += OnSectionChanged;
    }

    private void OnDisable()
    {
        _character.NarrativeDesign.OnSectionChanged -= OnSectionChanged;
    }

    // 由 UI 按钮调用
    public void SelectTopic(string triggerName)
    {
        _character.NarrativeDesign.InvokeTrigger(triggerName);
    }

    // 由自由文本输入框的提交事件调用——注入纯文本上下文
    // 角色用自己的措辞自然地回应
    public void AskFollowUp(string userQuestion)
    {
        _character.NarrativeDesign.InvokeSpeech(userQuestion);
    }

    // 需要播报预设公告时调用——角色会逐字照读
    public void AnnounceToUser(string announcement)
    {
        _character.NarrativeDesign.InvokeSpeech($"<speak>{announcement}</speak>");
    }

    private void OnSectionChanged(string previous, string next)
    {
        // 更新面包屑导航 UI——从 Manager 中查找便于用户理解的名称
        if (_narrativeManager.FindSectionConfig(next) is { } cfg)
            _activeTopicLabel.text = cfg.SectionName;
    }
}
```

在 Inspector 中为按钮分配触发器名称： `"TopicFacilities"`, `"TopicSystemsAccess"`, `"TopicPolicies"`.

将 `TriggerOnce = false` 设置为所有触发器的值，以便用户可以重新访问任意主题。在会话开始前，通过表单发送模板键（`UserName`, `Department`），使用 `UpdateTemplateKeys`.

`InvokeSpeech` 有两种模式：纯文本会让角色用自己的措辞自然地回应（适用于自由文本后续问题）；将消息用 `<speak>` 标签会让角色逐字说出该文本（适用于脚本化公告或精确提示）。两种模式都不会推进图。完整参考请参阅 [控制角色说话](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/narrative-design/scripting-narrative-design.md#control-character-speech) 。

### 示例 3：由接近触发的展品导览

**复杂度：** 中级 | **激活模式：** 接近 | **使用的功能：** Manager、Trigger（Proximity）、区域事件、批量模板键

**场景：** 某产品展厅设有五个展示站。访客走近每个展示站时，一名主持角色便开始介绍对应产品。每个展示站彼此独立，访客可以按任意顺序参观。

#### 设置

为每个展示站创建一个 `ConvaiNarrativeDesignTrigger` 。每个触发器的设置如下：

* **激活模式：** `Proximity`
* **接近半径：** 根据展示站大小调整（在 Scene 视图中显示为绿色球形辅助图标）
* **仅触发一次：** `true`
* **场景加载时重置：** `true` （这样每次访问时都会重置导览）

通过模板键传入各展示站的上下文。在 `ScriptableObject` 中定义数据，并在 `Start()`:

```csharp
[CreateAssetMenu(menuName = "Showroom/Station Data")]
public class StationData : ScriptableObject
{
    public string ProductName;
    public string LaunchYear;
    public string KeyFeature;
}

public class StationController : MonoBehaviour
{
    [SerializeField] private ConvaiNarrativeDesignManager _narrativeManager;
    [SerializeField] private StationData _data;

    private void Start()
    {
        _narrativeManager.UpdateTemplateKeys(new Dictionary<string, string>
        {
            { "ProductName", _data.ProductName },
            { "LaunchYear",  _data.LaunchYear  },
            { "KeyFeature",  _data.KeyFeature  }
        });
    }
}
```

使用 `OnPlayerEnterZone` 突出显示产品模型（例如，启用轮廓着色器）。使用 `OnPlayerExitZone` 移除高亮效果。

{% hint style="warning" %}
如果展示站的接近半径彼此重叠，两个触发器可能会在同一帧触发，并在后端响应第一个触发器之前发送两次图状态转换。请调整展示站的位置，避免接近区域相交；或者使用 Collision 模式，并将触发碰撞体彼此分开。
{% endhint %}

### 示例 4：带动态反馈的自适应场景

**复杂度：** 高级 | **激活模式：** 代码驱动 | **使用的功能：** 管理器， `IConvaiNarrativeDesign`, `OnSectionDataReceived`, `BehaviorTreeConstants`、动态模板键、重做流程

**场景：** 一名技术技能评估员运行一个多步骤场景。每完成一步，都会对学习者的表现进行评分。角色提供的指导程度和场景的挑战级别会根据当前累计得分动态调整。可以重新进行场景评估，并重置所有状态。

#### 会话生命周期

```mermaid
flowchart TD
    A[会话开始] --> B["UpdateAndSendTemplateKey\n(DifficultyLevel, Foundation)"]
    B --> C[角色进入对话\n→ FlushPending → 发送键]
    C --> D[场景开始\n首个部分处于活动状态]
    D --> E[学习者完成一步\n→ 由 ScenarioController 评分]
    E --> F["UpdateAndSendTemplateKey\n(DifficultyLevel, score > 80 ? Advanced : Foundation)"]
    F --> G[InvokeTrigger StepCompleted]
    G --> H[部分发生变化\n→ OnSectionDataReceived]
    H --> I[反序列化 BehaviorTreeConstants\n应用场景参数]
    I --> E
    E --> J{最后一步？}
    J -- 是 --> K[OnSectionStart Assessment Complete\n→ 显示分数摘要]
    K --> L{重新进行？}
    L -- 是 --> M[ResetController + FetchAndSyncFromBackend\n→ 重新开始]
    L -- 否 --> N[结束会话]
```

#### 实现

```csharp
public class ScenarioController : MonoBehaviour
{
    [SerializeField] private ConvaiNarrativeDesignManager _narrativeManager;
    [SerializeField] private ConvaiCharacter _character;

    private int _totalScore;
    private int _stepCount;

    private void OnEnable()
    {
        _character.NarrativeDesign.OnSectionDataReceived += OnSectionDataReceived;
    }

    private void OnDisable()
    {
        _character.NarrativeDesign.OnSectionDataReceived -= OnSectionDataReceived;
    }

    public void StartScenario(string learnerName)
    {
        _totalScore = 0;
        _stepCount  = 0;
        _narrativeManager.UpdateTemplateKeys(new Dictionary<string, string>
        {
            { "LearnerName",    learnerName   },
            { "DifficultyLevel", "Foundation" }
        });
        _narrativeManager.SendTemplateKeysUpdate();
    }

    public void OnStepCompleted(int stepScore)
    {
        _totalScore += stepScore;
        _stepCount++;

        string level = (_totalScore / _stepCount) > 80 ? "Advanced" : "Foundation";
        _narrativeManager.UpdateAndSendTemplateKey("DifficultyLevel", level);
        _character.NarrativeDesign.InvokeTrigger("StepCompleted");
    }

    private void OnSectionDataReceived(NarrativeSectionData data)
    {
        if (string.IsNullOrEmpty(data.BehaviorTreeConstants)) return;

        // BehaviorTreeConstants 是在 Convai 控制面板中编写的 JSON 字符串
        // 包含此部分的特定场景参数
        var constants = JsonUtility.FromJson<ScenarioConstants>(data.BehaviorTreeConstants);
        ApplyScenarioParameters(constants);
    }

    public async void RetakeScenario()
    {
        _narrativeManager.ResetController();
        await _narrativeManager.FetchAndSyncFromBackendAsync();
        StartScenario("LearnerName");
    }

    private void ApplyScenarioParameters(ScenarioConstants constants)
    {
        // 将在仪表板中配置的常量值应用到场景
    }

    [Serializable]
    private class ScenarioConstants
    {
        public float TimeLimit;
        public int   RequiredScore;
        public bool  ShowHints;
    }
}
```

`BehaviorTreeConstants` 是你在 Convai 仪表板中为每个小节编写的 JSON 字符串。它包含你希望从图中注入 Unity 的任意数据，例如时间限制、评分门槛、提示标记或其他场景参数。SDK 会在每个 `NarrativeSectionData` 负载中提供这些数据。

{% hint style="info" %}
`BehaviorTreeCode` 和 `BehaviorTreeConstants` 在 SDK 侧均为只读。它们包含在 Convai 仪表板中编写的数据，无法在运行时从 Unity 修改。
{% endhint %}

### 后续步骤

{% 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 %}

{% content-ref url="/pages/bd435d6564aabc01fda5fe6b7c130cf0ffeb1c36" %}
[排查叙事设计问题](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/features/narrative-design/troubleshooting-and-diagnostics.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/usage-examples.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.
