Documentation menu

Design patterns and best practices

Description: Common patterns for Narratyr projects

Variables vs. Functions

There are two ways to share state between Narratyr and your Game -- either through variables or functions. Which should you use and when?

A common example: Inventory

Lets say you want to know about the player's inventory in a quest. A common idea here might be to check if the player has retrieved a requested item, or customize dialogue based on the presence or absence of an item. One way to represent this would be through a variable:

An example inventory variable using set<entity_reference<item>> An example quest

In this example, the inventory is a set of Item entities (a set is like a list, but where duplicate entries are not allowed.) entity_reference<Item> is used here to allow Narratyr to know as much about the items as possible, but this isn't required. You could just as easily use a list<string> if you wished for more flexibility (duplicates and arbitrary strings)

What are the advantages to this?

  • Narratyr can handle save-game serialization for you.
  • Narratyr also has engine debuggers to display variables, so you can see the state in an editor window when debugging.
  • Quests and Dialogues always know what's happening

The disadvantages?

  • Narratyr doesn't support storing structures (outside of entities) in variables, so if your inventory items require a lot of metadata, you likely don't want to use Narratyr as your inventory system.
  • If your inventory is large and complex, you may need more complicated data structures than a list or set.

The alternate approach here would be to use functions:

Function example Gate example

In this example, there's: addInventoryItem(itemId, count), removeInventoryItem(itemId, count) and hasInventoryItem(itemId).

What are the advantages of this?

  • You can use any underlying data structure you want for your inventory, as long as you provide a set of functions to interact with it.
  • If you already have systems setup before you decided to use Narratyr, this can create a natural bridge.

What are the disadvantages?

  • More complex to build -- you need to write these functions in your game, then let Narratyr know about them. If the function changes in the game, you need to remember to update the definition in Narratyr.
  • Debugging becomes more complex. Because a function can do anything and Narratyr has no way to look into it, debugging becomes more challenging.
  • You need to let Narratyr know that you modified state, if you use functions in gates or event listeners, so those nodes know to re-evaluate their conditions. On the other hand, variables in Narratyr handle this automatically.
    • For example, if you were to update the inventory in the game, you need to let Narratyr know so it can rerun any pending hasInventoryItem calls. This is one function call so it's simple, but it's also easy to forget.
  • You'll need to handle save games yourself

Recommendation

Use variables when you can, because they're much simpler to manage and debug. Use functions when the underlying system is more complicated than is representable in Narratyr.

Visual ordering of nodes

When several connections leave the same output, Narratyr checks them in the top-to-bottom order of their target nodes. It follows the first connection whose condition passes. A connection without a condition always passes. This rule applies in both the simulator and exported games.

The target node's position on the canvas determines this order, including its position inside a comment container. Moving a bend in the connection doesn't change the order. This rule resolves competing connections from one output. It doesn't mean the whole graph runs from top to bottom.

Suppose an output has two connections:

  1. A connection to Open door, with the condition HasKey.
  2. A connection to Locked door, without a condition, as the fallback.

With Open door higher on the canvas, Narratyr checks HasKey first. If you move Locked door higher than Open door, Narratyr always takes the unconditional connection. Dragging nodes or using Auto Arrange can change the story's behavior without changing any conditions. Moving a comment container can also change the priority of connections to nodes inside it.

Here's a visual example. This version works correctly.

Key Example

And the same graph, but a different order:

Key Example Broken

Fortunately, there's an easy way to fix this!

Make branch priority explicit with a Hub

Use a Hub when branch priority matters. Give each Hub output one connection, then order the outputs by priority. The Hub tries its outputs in their listed order, regardless of where you place the target nodes. Put any unconditional fallback on the last output.

Example Hub Refactoring

Narratyr shows a warning icon beside the evaluation-order number on connections that depend on target position. Hover over the icon to read the warning. The validation panel also reports these connections and links to their source node.

For an ordinary output, such as an Instruction, Gate, or Dialogue without choice slots, select Convert to Hub in the warning. Narratyr inserts a Hub and gives each connection its own output, using the current top-to-bottom priority. It preserves the connections' conditions, labels, and targets. You can undo the entire conversion in one step.

Review the order before converting: conversion preserves the current priority, including an unconditional fallback that you placed first by mistake.

Convert To Hub Convert to Hub Finished

Multiple connections on an existing Hub output

The top-to-bottom rule still applies if you connect several targets to the same Hub output. Move those connections onto separate outputs of the original Hub, in the intended priority order.

Review what happens when every condition on an output fails. The original Hub can try its later outputs. An unconditional connection to another Hub commits to that route, even if the second Hub has no matching branch. Also review any traversed(...) checks that count uses of the original output, because splitting it creates separate output counts. Narratyr leaves this conversion to you.

Choice slots and Dialogue choices

A slot is one output row on a node. Multiple connections from one Choice or Dialogue choice slot also use target position to choose the first passing route. Separate slots represent separate player choices, so adding slots would change the menu the player sees.

To keep one choice with several possible destinations, route that choice to a Hub with one connection per Hub output. Make this change manually and check:

  • Availability: keep conditions that control whether the player can take the choice on the choice or its connection to the Hub. Moving all conditions after the choice can leave the player with a selectable option that leads nowhere.
  • Choice text: enter an explicit choice label if needed. A Dialogue choice with an empty label can borrow its destination's short text. Connecting it to a Hub removes that dialogue destination.
  • No matching route: decide what should happen when every branch condition fails, and test that case in the simulator.

Fork branches

A Fork starts concurrent branches. When a Fork output has several connections, the runtime checks them in the top-to-bottom order of their targets.

Keep the Fork for concurrency. You can route one of its outputs through a Hub, but review the conditions manually. A condition on the Fork's connection decides whether that branch starts. The runtime checks conditions on the Hub's outputs after the branch has started. Another branch may have changed the state those conditions read by then.

Listener priority

When eligible Event Listeners compete, the runtime uses their Priority values, highest first. Listeners with equal priority use their top-to-bottom canvas positions to break the tie. Set distinct priorities when their firing order matters.

A Hub controls routing after a listener fires. It doesn't replace listener priority. If the listener's own output has several connections, you can convert that output to a Hub. You still need to set listener priorities.

Arranging a graph with warnings

Auto Arrange asks for confirmation when the requested arrangement can affect connections that depend on visual order or listeners with tied priorities. This includes arranging a selection or the contents of a comment container.

Choose Cancel to fix the priorities first, or Arrange Anyway to proceed and review the result afterward. Arrangement doesn't insert Hubs or preserve implicit branch priority. Check the evaluation-order numbers and test the affected paths after arranging. AI arrangement reports these risks in its tool warnings. The same Hub and listener-priority guidance applies to generated graphs.

Dialogue Routing

Often, a character may be revisited multiple times in a game, and the conversation with them will evolve over time as the game evolves. It may be temping to create a dialogue graph for each individual interaction. This is completely reasonable, but it does leave it up to your game to choose the correct dialogue graph based on the current game state, which may move logic outside the dialogue system which belongs in the dialogue system.

An alternative approach is to make Dialogue graphs which are character-centric instead of interaction-centric. In this model, you would use a Hub node in order to route to the correct sub-graph based on Narratyr state. Here's an example:

Hub based on Objective State

In the above example, the conversation with Sandra changes based off the status of objectives and variables. This is admittedly a bit complicated looking though. One additional pattern you can use here is to use Start Dialogue to divide into sub-graphs.

Hub with Sub Graphs

First conversation introductions

Often in a game, you might want slightly different dialogue based on if this is the first time you've talked to a character. The first time you talk to a character they may introduce themselves, and in subsequent conversations they skip the introduction, for example.

Introduction with a boolean variable

A very straightforward way to accomplish this would be to use a boolean variable. You could check HasMetSally in the dialogue graph, and then update HasMetSally := true after the introduction.

Introduction Variables

There's an issue with this, however, which is that if you have a lot of NPCs you might end up with a variable per-NPC, which is a lot of variables. HasMetSally is fine, but 50 HasMetPerson variables can get annoying.

Reducing the amount of variables

A better way to do this is to use a set (a set is just a list where each item is unique

  • no duplicates). We can store the id of each character on a variable like Player_CharactersMet using an entity_reference.

Introduction Variables

Then we can use the in or not in operators to check if the character is in the set, and += to add the character.

Introduction Variables

#entity("SallyNPC") looks up the characters unique id via the External Id field set on the character. (External Id = SallyNPC)

Introduction Variables

Using zero variables

The previous way is the best practice for this. However, for completeness it's useful to consider another way we can an accomplish this.

To play an introduction once, route through a Hub and put this condition on its introduction connection:

traversed("introduction-output-id") == 0

Introduction Variables

Replace the string with the introduction output's ID, copied from the Hub's output controls. Put the usual greeting on a later output as the fallback.

The reason this works is Narratyr keeps a count of which nodes and edges have been activated by a flow player (this also gets stored in saved games, automatically). Following an output increases its count, which makes the introduction available on the first visit and skips it on later visits. Evaluating a condition leaves the count unchanged. An edge ID or the introduction dialogue node's ID works with traversed too.

Entity References can save you from bugs

Narratyr variables can store something called an Entity Reference, with a subtype of either any or a defined entity type (Character, Item, etc.). You can use these to reference an entity defined in the Narratyr project. The underlying type for this is simply a string, which is what your game code will see. The id string is something called a proquint, which is a random id that's designed to be pronounceable. If you have a character named Sally, and a variable that stores an entity reference, the value in the variable won't be the literal string Sally, it will be a unique id like mufob-kogoh-hafal-jatun (you can see this id in the entity editor page).

Why store an entity reference instead of a string containing the name? Both are valid approaches, the main advantage of an Entity Reference is that Narratyr understands it so it can survive renames and the validator will give you better checks (for instance, if you reference an entity that doesn't exist)