> 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/template-keys-dynamic-narrative-variables.md).

# 配置叙事模板键

设置叙事模板键，使 Convai 角色能够在其目标中引用运行时值——玩家姓名、场景参数或会话状态。

模板键是运行时键值对，用于填充角色叙事目标中的占位符。请在 [Convai 控制面板](https://convai.com) 中使用花括号语法定义占位符，例如： `{PlayerName}` 或 `{CurrentTask}` 。SDK 会在运行时从 Unity 发送实际值，让角色在对话中自然地引用这些值。这样，一个叙事图就能适用于包含不同参与者或动态状态的多个会话，无需每次都编辑叙事图。

#### 在 Inspector 中定义键

在 Inspector 中打开 `ConvaiNarrativeDesignManager` 并展开 **模板键** 折叠面板。

点击 **+** 添加一项。每项包含两个字段：

| 字段    | 说明                                      |
| ----- | --------------------------------------- |
| **键** | 占位符名称，必须与叙事设计部分目标中所写的完全一致（区分大小写，不含花括号）。 |
| **值** | 初始值。你可以在运行时通过代码覆盖此值。                    |

<figure><img src="https://2402152281-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FEtUJA212Zc1S9ACc8T4l%2Fuploads%2F1oLqJc5lARpRnWg4GsTJ%2Fimage.png?alt=media&amp;token=04e70067-f6b7-4cd3-8677-ed7193d0fa2b" alt="Template Keys foldout in the ConvaiNarrativeDesignManager Inspector with two key-value entries"><figcaption><p>ConvaiNarrativeDesignManager 中的模板键折叠面板。</p></figcaption></figure>

在 Inspector 中定义的键会在 `Awake` 时同步到内部控制器，并在会话开启时自动发送给 Convai。你无需手动调用任何内容来确保发送。

在 Play Mode 下，Inspector 中会显示一个 **发送到服务器** 按钮，点击后会立即调用 `SendTemplateKeysUpdate()`。无需编写代码，即可在会话过程中测试值的更改。

#### 在运行时更新键

使用 `ConvaiNarrativeDesignManager` 上的以下任一方法，通过代码更新键：

**更新单个键：**

```csharp
narrativeManager.UpdateTemplateKey("PlayerName", "Alex");
```

**更新并立即发送（一次调用）：**

```csharp
narrativeManager.UpdateAndSendTemplateKey("ScenarioPhase", "Handwashing");
```

当键更改需要从角色的下一次响应起生效时，请使用 `UpdateAndSendTemplateKey` 。

**一次更新多个键：**

```csharp
narrativeManager.UpdateTemplateKeys(new Dictionary<string, string>
{
    { "PlayerName", "Alex" },
    { "Department",  "Facilities" },
    { "CompletedSteps", "3" }
});
narrativeManager.SendTemplateKeysUpdate();
```

**读取当前键字典：**

```csharp
Dictionary<string, string> current = narrativeManager.GetTemplateKeys();
```

#### 键的发送方式

```mermaid
flowchart TD
    A["UpdateAndSendTemplateKey(key, value)"] --> B[UpdateTemplateKey\n更新 _templateKeys 列表和 Controller]
    B --> C[SendTemplateKeysUpdate\nSyncTemplateKeysToController]
    C --> D[Controller.SendTemplateKeysUpdate\n触发 OnTemplateKeysUpdateRequested]
    D --> E[ConvaiCharacter.NarrativeDesign.SetTemplateKeys]
    E --> F{是否正在对话？}
    F -- 是 --> G[ConnectionService.UpdateTemplateKeys\n立即发送]
    F -- 否 --> H[_hasPendingTemplateKeySync = true\n加入 FlushPending 队列]
    H --> I[会话开启 → FlushPending\n自动发送键]
```

如果角色断开连接后重新连接，SDK 会在内部调用 `MarkPendingReplayAfterDisconnect` ，因此最新的键值会在下次连接时重新发送。重新连接后，您无需手动重新发送键。

#### 键命名规则

| 规则                     | 示例                                                       |
| ---------------------- | -------------------------------------------------------- |
| 必须与仪表板中的占位符完全一致（区分大小写） | 仪表板： `{playerName}` → 键： `playerName` （而不是 `PlayerName`) |
| 开头或结尾不能有空格             | `"PlayerName"` ✓ — `" PlayerName"` ✗                     |
| 键字符串不能为空               | `""` 会被静默忽略                                              |
| 值可以是空字符串               | 键 `"OptionalField"` 值为 `""` 有效                           |

**合适的键名：**

| 键                      | 值示例          |
| ---------------------- | ------------ |
| `PlayerName`           | `"Maria"`    |
| `ScenarioLevel`        | `"Advanced"` |
| `CompletedCheckpoints` | `"4"`        |
| `SessionStartTime`     | `"09:15"`    |

**不合适的键名：**

| 键               | 问题                                                      |
| --------------- | ------------------------------------------------------- |
| `player name`   | 名称中有空格——无法匹配 `{player name}` 占位符；如果仪表板使用 `{playerName}` |
| `"PlayerName "` | 末尾有空格——不会匹配，且不会提示                                       |
| `""`            | 为空——会被忽略                                                |

{% hint style="danger" %}
模板键值会以纯字符串的形式通过网络发送，也可能出现在角色的对话中。请勿在模板键值中包含密码、个人身份识别号码、API 密钥或任何其他敏感数据。
{% endhint %}

#### 直接在角色上设置键

如果您没有使用 `ConvaiNarrativeDesignManager`，您可以通过角色 API 直接设置模板键：

```csharp
ConvaiCharacter character = GetComponent<ConvaiCharacter>();

// 单个键
character.NarrativeDesign.SetTemplateKey("PlayerName", "Alex");

// 多个键
character.NarrativeDesign.SetTemplateKeys(new Dictionary<string, string>
{
    { "PlayerName", "Alex" },
    { "Department", "Engineering" }
});
```

角色 API 和管理器 API 最终都会在内部调用同一个 `ConnectionService.UpdateTemplateKeys` 方法。在同一个项目中，您可以使用任一路径，但请避免在同一帧内通过两种路径设置同一个键，否则可能会发送重复更新。

#### 后续步骤

{% 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/template-keys-dynamic-narrative-variables.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.
