Skip to content

Using stories in games

A Bruja story doesn’t draw anything. Your game asks it for the next line, shows that line however it likes, and tells it which choice the player picked. This page shows how, first in plain C# (any .NET game or tool) and then in Unity.

Contents


The two assemblies

Assembly What it does Ship it in your game?
Bruja.Runtime Plays compiled stories: the Story class, values, save/load. No dependencies, no reflection on the hot path; works on Mono and IL2CPP. MIT license. Yes
Bruja.Compiler The compiler (.bruja source to bytecode). Depends on ANTLR. MPL-2.0 license. Only if the game compiles source at runtime (editors, modding)

Both target .NET Standard 2.1 and .NET 10, and are on NuGet under the same names. Everything is in the Bruja namespace.

Playing a story

Bruja works like Ink: you pull one line at a time.

using Bruja;

var story = new Story();
story.Start(File.ReadAllText("intro.bruja"));   // compiles (needs Bruja.Compiler) and starts

while (story.CanContinue)
{
    string? line = story.Continue();          // runs to the next line of dialogue
    if (line != null) ShowLine(line, story.CurrentTags);

    if (story.CurrentChoices.Count > 0)       // the line was a question
    {
        foreach (StoryChoice choice in story.CurrentChoices)
            ShowChoiceButton(choice.Index, choice.Text, choice.Tags);

        int picked = await WaitForPlayerToPick();
        story.ChooseChoiceIndex(picked);
    }
}
// story.IsFinished is true here
  • Continue() returns the text of the next > line. When that line asks a question, CurrentChoices holds its choices and you must call ChooseChoiceIndex before continuing.
  • Continue() returns null when the story stops without a line: at a wait (see below) or at the end.
  • Choices hidden by a {condition} or already used up are not in CurrentChoices, and fallback choices are taken for you. Pass choice.Index back, not the position in your own UI.

Markup (<b>, <color=red>, <pause=0.5>, your own tags) is never in Continue()’s text. Read it one of two ways:

tmpText.text = story.CurrentRichText;          // "It was <b>huge</b>." for TextMeshPro

foreach (TextSpan span in story.CurrentSpans)   // or build the text yourself
{
    if (span.Mark != null)                      // a self-closing tag: <pause=0.5>, <sfx=door/>
    {
        if (span.Pause > 0) yield return new WaitForSeconds(span.Pause);
        else if (span.Mark.Name == "sfx") audio.Play(span.Mark.Value);
        continue;
    }
    bool bold = span.Has("b");
    string color = span.ValueOf("color");     // "red", "ff8800" (hex without '#'), or null
    Type(span.Text, bold, color, shake: span.Has("shake"));
}

CurrentRichText leaves pauses out, adds # to hex colors and wraps a < that is part of the text in <noparse>, so it can go straight into TextMeshPro. Your own tags stay in it (TextMeshPro understands some, like <sprite=1> and <mark>). Choices have the same: choice.RichText and choice.Spans; choice.Text is plain.

Localization. Lines with IDs (#line:g01, see the language reference) can be shown in another language from a string table: the CSV that bruja lines export writes, with the text column translated.

story.SetStringTable(StringTable.FromCsv(File.ReadAllText("fr.csv")));   // switch at any time
story.SetStringTable(null);                                               // back to the original
story.SetLineLookup(id => myLocalization.Get(id));                        // or your own source
string? id = story.CurrentLineId;                                         // "g01", e.g. for voice-over

Lines missing from the table show the story’s own text. Choices have choice.LineId. The table isn’t saved with the story: set it again after LoadState. Localization covers exporting, checking and voice-over.

Jump to a thread with story.GoTo("chapter_two.attic") (or just "attic" if it’s unique), and read how often a thread was entered with story.VisitCount("attic"). story.TurnCount is the number of choices made, and story.TurnsSince("attic") the turns since the story was last there (-1 if never).

Tags, waits and game functions

Tags (> Halt! #speaker:guard #vo:guard_01) arrive without the #:

foreach (string tag in story.CurrentTags)   // "speaker:guard", "vo:guard_01"
{
    if (tag.StartsWith("speaker:")) portrait.Show(tag.Substring(8));
    if (tag.StartsWith("vo:")) audio.PlayVoice(tag.Substring(3));
}

Choices have their own tags in StoryChoice.Tags. The speaker shorthand (> @guard (stern): Halt!) arrives as ordinary tags too: "speaker:guard", "portrait:stern".

Waits (wait "door_opens") stop Continue() with a null line and set CurrentWait:

string? line = story.Continue();
if (line == null && story.CurrentWait is DynamicValue wait)
{
    if (wait.IsString) await PlayCutscene(wait.StringValue);
    else if (wait.IsInt || wait.IsFloat) await Delay((float)wait);
    // then keep calling Continue()
}

Text input (name = input("What's your name?", "Alex")) also stops Continue() with a null line; CurrentInput holds the question and CanContinue is false until you answer:

if (line == null && story.CurrentInput is StoryInput input)
{
    string typed = await ShowTextField(input.Prompt, input.Default);   // input.Tags too
    story.SubmitInput(typed);   // input() returns this; then keep calling Continue()
}

With push-style Execute(), override TextHandler.HandleInput(StoryInput) and return the text.

Game functions are C# functions the script can call. Bind them before starting the story; scripts declare them with extern giveItem, playSound.

story.Bind("giveItem", args =>
{
    inventory.Add(args[0].StringValue);
    return DynamicValue.Null;
});

story.Bind("hasItem", args => inventory.Contains(args[0].StringValue));   // returns a bool

The args => ... form (a NativeFunction) is the fast path: no reflection and no allocation per call, so it’s the one to use on IL2CPP. Any other delegate works too (story.Bind("roll", (Func<int, int>)Roll)) with its arguments converted by reflection.

Bindings are not saved in save games; bind them again before loading one.

Variables

story.SetVariable("playerName", "Ash");      // before Start, or between Continue()s
story.SetVariable("mood", story.EnumMember("Mood.sad"));   // a member of `enum Mood` (after Start)
int gold = (int)story.GetVariable("gold");
story["gold"] = 10;                            // same as SetVariable

story.ObserveVariable("hp", (name, oldValue, newValue) => healthBar.Set((int)newValue));

Values are DynamicValues. Check the type with IsInt, IsString, IsBool, IsNull, … and read them with IntValue, StringValue, … or cast: (int)value, (string?)value, (StoryArray?)value. C# int, float, bool and string convert to DynamicValue automatically. A member of a story enum has IsEnum, EnumName ("Mood") and MemberName ("sad"); get one to set with story.EnumMember("Mood.sad").

Events

A script can declare an event and fire it; C# can listen, and fire events the script listens to:

event enemyDefeated
enemyDefeated += name => print(name + " is down")
enemyDefeated("wolf")
story.OnEvent("enemyDefeated", args => { achievements.Count(args[0].StringValue); return DynamicValue.Null; });
story.FireEvent("dayChanged", 3);   // runs the script's handlers to completion; call between Continue()s

Save games

byte[] save = story.SaveState();

// Later, maybe in a new session:
var story = new Story();
BindGameFunctions(story);
story.Start(program);          // the same compiled story
story.LoadState(save);
// story.CurrentText, CurrentTags and CurrentChoices are back as they were.

A save holds everything: variables, where the story is (even inside a function, a loop or a generator), paused generators, the current question, which once-only choices were used, how far each text variation has got, turn counts, and the random generator. It doesn’t hold bindings or your observers.

Saves are format 5. Saves from 1.0 (format 4) and earlier format 3 still load; they didn’t keep turn counts, so turns() starts again from 0.

Errors

Compile errors. story.Diagnose(source, "intro.bruja") returns every problem as StoryErrors (file, 1-based line and column, message, Severity), without running anything. Compile throws SyntaxException on the first error. Errors are things like syntax mistakes, unknown thread names in ->, or assigning a const; warnings are names that are never assigned (usually typos, or a game function missing its extern).

foreach (StoryError e in story.Diagnose(source, "intro.bruja"))
    Console.WriteLine(e);   // intro.bruja:12:5: warning: 'golld' is never assigned. ...

Runtime errors (dividing by zero, error("..."), a failed assert, calling something that isn’t a function) throw StoryRuntimeException from Continue(). Its message ends with the location (at intro.bruja:12:1), File/Line/Column hold it separately, and ScriptStackTrace lists the script call stack. story.ErrorRaised fires first. The story is finished afterwards; load a save or start again.

A script that runs too long without showing a line (an infinite loop) stops with an error after StoryOptions.Interpreter.MaxInstructionsPerContinue instructions (100 million by default).

Editor support

Tools that edit stories (an in-game editor, a language server) can ask where things are:

  • Bruja.Tooling.StoryOutline.Analyze(source) (compiler assembly) lists the threads, functions (with parameters and the comment above them), variables, constants, locals, game functions and events a story defines, with 1-based positions. It works while the source has errors.
  • story.CurrentLine is the source line of the dialogue line, question or wait the story is paused at, for highlighting “where the story is”.

Randomness

Dice (d20), math.random and random text variations all use one generator. Seed it to make a playthrough repeatable, for tests or replays:

story.Random.Seed(42);

The generator’s state is part of save games, and gives the same numbers on every platform.

Compiling ahead of time

Players don’t need the compiler. Compile .bruja files when you build the game and ship the bytecode (.brujac):

// At build time (needs Bruja):
var compiler = new Story();
StoryProgram program = compiler.Compile(source, "intro.bruja");
File.WriteAllBytes("intro.brujac", compiler.Encode(program));

// In the game (Bruja.Runtime only):
var story = new Story();
story.Start(File.ReadAllBytes("intro.brujac"));

Stories in several files (import "chapter2.bruja") compile into one program. Compile from the main file with compiler.CompileFile("Stories/intro.bruja"), which reads imports from disk, or tell the compiler where files come from (a mod folder, an asset bundle, a dictionary):

var compiler = new Story(new StoryOptions
{
    Compiler = { ResolveImport = path => files.TryGetValue(path, out var text) ? text : null }
});
StoryProgram program = compiler.Compile(files["intro.bruja"], "intro.bruja");

path is relative to the main file’s name, with /. Errors (StoryError.Filename, SyntaxException.File, StoryRuntimeException.File) and story.CurrentFile / story.CurrentLine say which file a line is in.

The CLI does the same: bruja compile -f intro.bruja writes intro.brujac. Bytecode compiled by one Story plays in any other; names are relinked when it loads.

Playing push-style

For tools and quick tests you can have the story push text to you instead. Subclass TextHandler, pass it in StoryOptions, and call Execute:

class ConsoleHandler : TextHandler
{
    public override void HandleText(string text) => Console.WriteLine(text);

    public override void HandleQuestion(string question, string[] choices)
    {
        Console.WriteLine(question);
        for (int i = 0; i < choices.Length; i++) Console.WriteLine($"{i + 1}. {choices[i]}");
        Continue(int.Parse(Console.ReadLine()!) - 1);   // answer now, or later with ChooseChoiceIndex + Resume()
    }
}

var story = new Story(new StoryOptions { Interpreter = { TextHandler = new ConsoleHandler() } });
story.Execute(source);

story.Return("1 + 2") evaluates code and returns its value, which is handy for consoles and tests. print(...) goes to StoryOptions.Interpreter.Print (the console by default).


Unity

The Unity package is in unity/com.halfhumangames.bruja (Unity 2021.3 or newer). Add it with Package Manager → Add package from git URL:

https://git.halfhumangames.com/snarlynarwhal/Bruja.git?path=/unity/com.halfhumangames.bruja#v1.0.0

or Add package from disk → its package.json in a clone. unity/SampleProject is a ready-made project that uses it.

Importing. .bruja files in your project become story assets (StoryAsset). The importer compiles them in the editor, so players get bytecode and never parse source. Errors and warnings show in the Console (click to select the asset) and in the asset’s inspector. Edit the file and Unity recompiles it on save.

Playing. Add a Story Runner component, assign the story asset, and listen to its events:

using Bruja;
using Bruja.Unity;
using UnityEngine;

public class Dialogue : MonoBehaviour
{
    public StoryRunner runner;

    void Awake()
    {
        runner.Setup(story =>   // runs before the story starts (and again after loading a save)
        {
            story.Bind("giveItem", args => { Inventory.Add(args[0].StringValue); return DynamicValue.Null; });
            story.ObserveVariable("hp", (name, before, after) => HealthBar.Set((int)after));
        });

        runner.LineShown    += (text, tags) => ui.ShowLine(text, tags);
        runner.ChoicesShown += choices => ui.ShowChoices(choices, index => runner.Choose(index));
        runner.WaitRequested += wait => StartCoroutine(HandleWait(wait));   // then runner.Next()
        runner.Finished     += () => ui.Close();
        runner.ErrorRaised  += error => Debug.LogError(error);
    }

    // Call when the player clicks to continue:
    public void OnContinueClicked() => runner.Next();
}
StoryRunner
storyAsset the story to play
beginOnStart start in Start(); otherwise call Begin()
advanceOnBegin show the first line right away
autoContinueNumericWaits wait 2 waits 2 seconds and continues by itself; other waits raise WaitRequested
randomSeed 0 = different every playthrough
localization, SetLocalization(csv) the string table to play in (a .csv TextAsset); switch language with SetLocalization
richText on (default): LineShown gets the line with its markup (CurrentRichText), ready for TextMeshPro; off: plain text
onLine, onChoices, onFinished, onError UnityEvents, for wiring in the inspector
Next(), Choose(index) advance, answer a question
InputRequested, onInput, Submit(text) the story asks for text (input()): show a field, then submit what was typed
SaveToString(), LoadFromString(s) save games as a string (e.g. for PlayerPrefs)
Story the underlying Story, for everything else in this page

Without the runner, storyAsset.CreateStory() gives you a started Story to drive yourself.

Edit this page