Skip to content

Unity

Patterplay for Unity is the native C# Patterplay runtime: no web view, no JavaScript, no IPC. It loads a .patterc bundle and plays it directly, held to the same shared test suite as every other engine.

Needs Unity 6 (6000.x), the version it’s verified on. Some C# is expected, this is the game-developer side of the project.

Patterplay ships as a UPM package and must be installed as a package (its Newtonsoft Json dependency only resolves then). Get it from the play-unity-v* Release (see the downloads page), any of:

  • Unzip the release, then open Package Manager ▸ Install package from disk… and pick the Patterplay/ folder’s package.json.
  • In Package Manager ▸ Add package from git URL…, paste the package’s git URL (the Release lists it).
  • Copy the zip’s Patterplay/ folder into your project’s Packages/ directory using your file browser, which embeds the package in the project.

Don’t drag the folder into the Unity Project window: even dropped onto its Packages section, Unity imports it into Assets/ as loose scripts, where the package manifest is ignored and the Newtonsoft dependency never installs (a wall of Newtonsoft could not be found errors). Only the file browser or Package Manager can install a package.

A compiled .patterc is recognised by a ScriptedImporter: drop the file into your project and Unity converts it to a PatterBundleAsset (with a custom inspector). Reference that asset wherever you build an engine.

Build an engine from the bundle asset, open a flow, and advance it. The play loop is the same shape as everywhere else: here it is in C#:

using UnityEngine;
using Patterkit.Patterplay;
public sealed class StoryRunner : MonoBehaviour
{
public PatterBundleAsset Bundle; // the imported .patterc
void Start()
{
var engine = Bundle.CreateEngine();
PatterDebug.Register(engine); // optional: lets the state window watch it
var flow = engine.OpenFlow("main", "intro"); // ("flow id", starting scene/block)
for (;;)
{
var step = flow.Advance();
switch (step.Type)
{
case StepType.Line: Debug.Log($"{step.SpeakerLabel ?? step.Character}: {step.Text}"); break;
case StepType.Text: Debug.Log(step.Text); break;
case StepType.GameEvent: /* play step.GameData cues */ break;
case StepType.Choice:
var pick = step.Options[0]; // your UI chooses; demo takes the first
flow.Choose(pick.Id);
break;
case StepType.End:
Debug.Log($"[end] @gold = {engine.GetProperty("@gold")}");
return;
}
}
}
}

Drop that on a GameObject, assign the imported bundle to the Bundle field, and press Play. Render each step into your own dialogue UI; on a Choice, show step.Options (each has a Prompt and an Eligible flag) and call flow.Choose(id) with the player’s pick. A line’s Qualifier is its speaker qualifier by its gameId (vo, os, radio), and QualifierName its localised shown name; a line prompt carries both too. Show SpeakerLabel as the speaker’s name: it’s localised and already puts the two together the way the writer and the translator chose (see How a qualified speaker is shown). A Line or Text step’s PadAfter (a double?, null on the other steps) is the writer’s pause after it in seconds, already resolved; Bundle.DefaultPadAfter (0.6) is the one a project gets when it sets none. The timing rules say how to play it, and Bundle.EstimateLineDuration(step.SpokenText, step.SpokenLocale, step.EstimateSpeed ?? Bundle.DefaultEstimateSpeed) how long a line with no recording lasts: SpokenText is the line in the project’s main language, the one it’s spoken in, whatever language is shown (null in an IDs-only bundle), and EstimateSpeed the project’s speed for an estimate (1 unless the writer changes it, higher is faster). A Text step with Action set is action, a direction for whoever stages the scene: stage it, or let it pass, but don’t show it as on-screen text. Action is false on shown text and on a replayed prompt.

engine.OpenFlow("main") with no scene starts at the project’s start scene (Bundle.Start), or at the first scene when the project sets none. A step’s GameData and Tags, and an option’s GameData, are your own copies: edit them freely. A step’s Extensions are the bundle’s own, so treat them as read-only. A choice’s prompts are built each time it’s delivered, so SetLocale reaches a choice already on screen.

The engine never stops the story for a problem: it carries on and reports it to EngineOptions.OnError as a PlayError (or, with no handler, as a [Patterplay] warning). Its Kind says what it was: a condition, effect, or best-match that failed at run time; setup, how the engine was built (a locale the bundle doesn’t have, a host scope it doesn’t declare), reported as the constructor ends; save, a load whose place has gone from the build; or dry-choice, a choice that ran dry with nothing after it, so the flow ended there (the end step’s Reason is then FlowEndReason.RanDry, otherwise FlowEndReason.Ended). A locale resolves by one rule: the locale itself, then its language (fr for fr-FR), then the bundle’s default. engine.Locale is the one in use, and engine.Locales the bundle’s Default and Included.

Two ready-made samples ship with the package. Import them from Package Manager ▸ Patterplay ▸ Samples. Each carries a ready-made scene, so there is nothing to set up: import, open the scene, press Play. The Tour demo (Tour.unity) plays the full interactive Patter tour as an OnGUI transcript with clickable choices; the minimal Play-through demo (PlayThrough.unity) is the smallest possible integration to read first. The tour sample also shows per-line audio resolution via PatterAudioResolver; audio files are not bundled (playback is your platform call), so point its Audio Root at a Patter audio folder to hear it, or leave it empty to play silently.

The story reads your game’s state as @world properties, and you give it that state by binding a World. The quickest way needs no code to bind it:

  1. Add a Patter World component (PatterWorld) to a GameObject, your game manager say.
  2. Drag that GameObject into the World field of the Patter Runner Behaviour (or of any component that builds its engine from a bundle asset and has a World field).
  3. Have your game write its state into the Patter World as it changes:
world.SetBool("has_key", true);
world.SetString("time_of_day", "night");
world.SetReadOnly("time_of_day", true); // yours alone: a story write is refused
world.Changed += (name, value, fromStory) => { /* the story wrote one back */ };

A condition on @world.has_key now reads your value, and an effect that sets @world.reputation writes it back. PatterWorld keeps typed Set* / Get*, Has, Names, SetReadOnly, and a Changed event that tells your own writes from the story’s. Names match case-insensitively, as the story’s references do. If your state already lives in a component of your own, implement IHostScope on it (below) and drag that in instead, or subclass PatterWorld and override Get and Set.

With nothing in World, the engine still plays: it self-backs @world from the declared defaults, so “has the key” reads the default and never sees your game. The runner says so once as it wakes, with a warning naming the component, so an empty field doesn’t go unnoticed.

In code, Bundle.CreateEngineWithWorld(world) takes the same World, and Bundle.DeclaresWorld says whether the story reads @world at all. A game that builds engines itself can also hand the engine its @world values through EngineOptions.HostScopes, an IHostScope per token (Get / Set, keyed by property name) that the story reads before every condition and writes through on an effect. Bind the same object to anything else that shares those values:

using Wildwinter.Expr; // ExprValue, the value type
sealed class WorldScope : IHostScope
{
public readonly Dictionary<string, ExprValue> Values = new() { ["time_of_day"] = ExprValue.Str("night") };
public ExprValue Get(string name) => Values.TryGetValue(name, out var v) ? v : null; // null = unset
public void Set(string name, ExprValue value) => Values[name] = value;
}
var world = new WorldScope();
var engine = Bundle.CreateEngine(new EngineOptions { HostScopes = new() { ["world"] = world } });

A World and HostScopes are the same binding, so CreateEngineWithWorld(world, options) refuses options that also bind world (an ArgumentException). Each binding is registered as a foreign scope: the values stay in your object, and no Patterplay save holds them, so your game saves them. Leave HostScopes null and a standalone engine self-backs @world from the declared defaults, as a property it stores and saves with the rest of the run. A property declared writable: false in the project is the story’s promise, so the engine refuses the story’s write with '@world.x' is read-only, bound or self-backed. Your own SetProperty isn’t refused for that, because the value is the game’s. It does throw, changing nothing, on a value that doesn’t fit the declaration ("@world.alarm" takes true or false; "yes" doesn't fit) or a name the project doesn’t declare; a scope that declares no names takes anything. A host-scope token is case-sensitive: one the bundle doesn’t declare is reported (setup), never folded. A per-name policy of your own is yours to refuse from Set. World Properties has the full picture.

Every property value lives in a registry, a ScopeRegistry. A game has one, and it holds every property from every engine in the game, except values your game keeps itself behind an IHostScope. The registry is saved and loaded as one.

An engine you build without one makes its own and acts as its own game, which is why a single PatterSave.SerializeState needs no wiring. A game that runs more than one engine (Patter beside the Storylet Engine, say), or that wants to hold the properties itself, makes the registry and hands it to each engine through EngineOptions.Registry:

using Newtonsoft.Json.Linq;
using Wildwinter.Expr; // ScopeRegistry, ExprValue
var registry = new ScopeRegistry().DefineOwned("world", new[]
{
new ScopeDeclaration { Name = "gold", Type = "number", Default = ExprValue.Num(0) },
}, new OwnedScopeOptions { Owner = "Game" }); // @world, stored and saved
var patter = Bundle.CreateEngine(new EngineOptions { Registry = registry });
// One save for the game: the registry's values once, and each engine's part.
var save = new JObject
{
["registry"] = PatterSave.SaveRegistry(registry),
["patter"] = PatterSave.SaveState(patter),
};
// Load in either order: values for bags that aren't open yet wait in the registry.
PatterSave.LoadRegistry(registry, (JObject)save["registry"]);
PatterSave.DeserializeState(patter, save["patter"].ToString());

Given a registry, the engine registers @patter under patter and each flow’s and scene’s bag under a key starting patter/, which no expression can name. Its save then leaves the values out, because your game saves the registry. @world is yours to register: owned, as above, when the registry should store and save it, or bound through HostScopes, when your game keeps the values. The engine self-backs nothing on a registry you pass. Every expression can read every registered scope.

Other engines’ scopes need no setting. A Patter line can name the Storylet Engine’s @story.act (in a condition, an effect, or a {@story.act} slot) in any project: the compiler lets it through without checking its names, since the Storylet Engine owns them, and the bundle lists it. Give every engine the game’s one registry: OpenFlow and LoadGame refuse content that names a scope no engine on the registry has registered, before anything changes, with the error this content names @story, which no engine on this registry registered: give every engine the game's one registry. If the other engine takes its scope away mid-game, a write to it fails naming the scope rather than landing in @patter.

A token is taken once. Two engines that both want the same one fail as you build the second, with an error that names who got there first, and your registry is left as it was. Rebuilding an engine on an edited bundle (HotSwap) hands its bags to the replacement on the same registry.

The registry, the value type ExprValue, and the rest of the shared expression kernel live in the Wildwinter.Expr namespace, in their own assembly, Patterplay.Expr. The Storylet Engine carries the same kernel, and with both packages installed it compiles once, in Patterplay, so one ScopeRegistry is the same type to both engines. The Storylet Engine names the Patterplay it needs, and stops the compile with an error saying so if it finds an older one. If your scripts have their own assembly definition, reference Patterplay.Expr and StoryletEngine.Expr beside Patterplay.Runtime: Unity ignores whichever is not installed. The engine’s own errors are still EvalError; a call you make straight to the registry throws the kernel’s RegistryError.

The game can also decide where the story goes. RunFlow plays an address in one call, which is all a bark needs:

// Reuses the "guard-42" flow, so its shuffles and once-each lists keep their place
List<StepResult> lines = engine.RunFlow("guard-42", "npc-barks", "greet");
foreach (var line in lines) Debug.Log($"{line.SpeakerLabel ?? line.Character}: {line.Text}");
// Or move a flow you are already driving, exactly as an authored jump would
if (!flow.Goto("throne-room", "audience")) { /* did not resolve; the cursor has not moved */ }

Give each independent speaker its own flow name. Full rules, and why OpenFlow behaves differently: Host navigation.

For a letter, a book page, or a sign, RunText gives you the block’s text as one string. It refuses dialogue and choices, and throws if it meets either (Show a block of text):

string letter = engine.RunText("correspondence", "from-mother");

The package adds Window ▸ Patterplay ▸ Runtime State: register a running engine with PatterDebug.Register(engine) and the window shows its @patter properties live, with type-aware editors (toggle / number / text / enum / flags) and a reset-to-default arrow that write straight back into the running game. It also has Save State… / Load State… buttons that persist the whole run to a .patterstate JSON file. The window is an editor-only tool (it lives in an Editor assembly), so it never ships in a player build.

PatterDebugLink streams the running story position back to Patterpad so the editor follows the cursor like a debugger. Wire it behind #if UNITY_EDITOR || DEVELOPMENT_BUILD so it is stripped from a release player build:

#if UNITY_EDITOR || DEVELOPMENT_BUILD
_link = new PatterDebugLink(engine.BuildId, "My Game");
_link.FlowOpened("main");
// ...after each Advance()/Choose():
_link.Observe("main", flow.CurrentScene, step.Id, PatterDebugLink.TypeName(step.Type));
#endif

The protocol and the editor side are on Live refresh & debug.

PatterSave.SerializeState(engine) and DeserializeState(...) round-trip the whole run: every flow’s position, visit counts, selector cursors, and the PRNG, as a tagged JSON envelope. An engine you built on its own also carries every property value, @patter, @scene, and a self-backed @world alike, so one call is still the whole game; an engine you gave a registry leaves them to the registry’s save. It is the same patter/save@0 format every Patterplay runtime uses, so a save written by a web build or by Patterpad loads here, and a save written here loads in Godot or Unreal. Saves are version 4: a pending choice is saved by its options’ ids, not their text, so it loads in the language of the engine that loads it. A version 3 save still loads, and is written back as version 4 on the next save; older saves don’t load in 1.0. A save loaded into an edited build finds its place by id and, where that place has gone, resumes at the nearest safe point and reports it (save). Persist the string wherever you keep saves, and see Save/load & Game Data for the format.

To set one flow aside instead, engine.CaptureFlow(id) returns its part of a save as a FlowState, and engine.RestoreFlow(newId, state) opens it again later; PatterSave.SaveFlowState and ReadFlowState turn a state into JSON and back. See Taking one flow out.

PatterplayVersion.Current is the runtime’s version, as in its package manifest ("1.0.0"). An extension that ships apart from Patterplay checks it at start-up with PatterplayVersion.InRange(PatterplayVersion.Current, "1.0.0", "2.0.0"): at least the first version and below the second, by semantic-version order. Every runtime has the same pair.

Open source under the MIT licence, made by .