Skip to content

Tutorial 12: Write your own node

A node of your own, Oldest Of Clan, that appears in the Studio’s search menu. It takes an actor, finds the oldest living member of that actor’s clan, and keeps them in a scheme variable. It has two outputs, Found and Not Found. At the end you add a second node that keeps a small state across a save.

A node is one C# class. The Studio finds it, lists it in the Add Node window, draws its card and builds its Inspector from its public fields. If you only need to call a method of your code from a scheme, you do not need a node: see Tutorial 9 and Code methods. Write a node when you want your own card, your own outputs or your own Inspector fields. The reference is Writing a custom node.

You need a Unity project with the Intrigues package and a scheme that has an Actor variable. If your code sits in its own assembly definition, reference MrW.Intrigues.

A node is a [Serializable] class that derives from NodeData, with a public constructor that takes no parameters, which the default one already is. Put [GraphNode] on it, because a class without it is logged as an error and the Studio will not offer it to anyone.

The three arguments are the title on the card, the menu path in the Add Node window, and a NodeCategory. The first segment of the path is the group. This node goes under Code. Description is the sentence in the Inspector header and the search tooltip. AfterLoad = AfterLoadMode.Safe says that running it again after a load is harmless. This node never waits, so a load never finds a visit of it half done.

Settings are public fields, and the Inspector is made from them, so a field you add later shows up there without more work.

  • ActorRef Who is the picker the built-in nodes use. Never store an actor in a field. An ActorRef resolves to the actor at run time, or to null when it is not available.
  • string StoreIn with [IdPicker(IdKind.SchemeActorVariable)] is a picker for an Actor variable of the scheme. The field keeps the variable’s ID.

SyncOutputs declares them. The Studio calls it after the node is created, after it is loaded and after every edit, so the outputs always match the settings. Two names, two outputs, numbered 0 and 1.

Describe writes the lines on the card and the problems the Studio shows. Keep it to string code, since it must not touch the scene or use editor-only calls. d.Line adds a line, d.Error and d.Warn add a problem, and Who.Describe(d) writes the actor’s name in words and adds an error when nothing is chosen.

Run is called each time a flow reaches the node. Follow the rules:

  1. Call flow.Begin() first.
  2. End every path with flow.Next(i), flow.End() or flow.Stop(reason). A path that does none of them keeps the scheme alive forever.
  3. Return a completed task for work done at once.

That is the whole contract. Everything else is your own code.

Create OldestOfClanData.cs. A node is runtime code. It does not go in an Editor folder.

Example. Compiled against the package’s runtime assembly; not run in Unity.

using System;
using System.Threading.Tasks;
using UnityEngine;
using MrW.Intrigues;
using MrW.Intrigues.Graph;
[Serializable]
[GraphNode("Oldest Of Clan", "Code/Oldest Of Clan", NodeCategory.Code,
Description = "Finds the oldest living member of an actor's clan and keeps them in a scheme variable.",
AfterLoad = AfterLoadMode.Safe)]
public sealed class OldestOfClanData : NodeData
{
[Tooltip("The actor whose clan is searched.")]
public ActorRef Who = ActorRef.Conspirator;
[Tooltip("The Actor variable of this scheme that gets the oldest member.")]
[IdPicker(IdKind.SchemeActorVariable)]
public string StoreIn;
public override void SyncOutputs() => SetOutputs("Found", "Not Found");
public override void Describe(NodeDescription d)
{
if (string.IsNullOrEmpty(StoreIn)) d.Error("Choose the variable that gets the oldest member.");
d.Line($"Oldest living member of the clan of {Who.Describe(d)}");
}
public override Task Run(NodeInfo flow)
{
flow.Begin();
var actor = Who.Resolve(flow);
if (actor == null)
{
flow.Stop("The actor is not available.");
return Task.CompletedTask;
}
Actor oldest = null;
if (actor.Clan != null)
foreach (var member in actor.Clan.Members)
if (member.State == Actor.LifeState.Alive && (oldest == null || member.Age > oldest.Age)) oldest = member;
ActorStore.Put(flow, StoreIn, oldest);
return flow.Next(oldest != null ? 0 : 1);
}
}

What each part does:

Part Source
ActorStore.Put(flow, StoreIn, oldest) stores the actor in the scheme variable. A null empties the variable, so a miss never leaves an older value behind. ActorStore.cs
flow.Next(0) and flow.Next(1) follow the output by its number. NodeInfo.cs
flow.Stop(reason) ends the visit. The reason goes to the Console when Verbose logging is on in the Studio settings. NodeInfo.cs, custom-nodes
Keep the class name, the field names and the order of the outputs once the node is used in a database. They are stored in it. UPGRADE_GUIDE.md

Do not rename the class: its type name is the serialized identity of every stored node of that type, so a rename loses those nodes (NodeData.cs), and the same goes for the field names and the order of the outputs that SetOutputs sets.

Let Unity compile, open a scheme, click the canvas to give it the focus, and press Space with the pointer where you want the node. In the Add Node window, open Code. Oldest Of Clan should be in the list, next to Run Code and Get From Code. Add it, set Who, and pick the Actor variable in Store In. The card shows Oldest living member of the clan of .... Link Found and Not Found to the nodes that follow.

  • The card. With Store In empty, the Studio shows the error from Describe. Pick a variable and it goes.
  • A run. Start the scheme in Play mode, as in Tutorial 9, and read the variable in a later node. In Tutorial 9, call.Named("Elder") reads exactly such a variable. Whether a Test run in the Studio runs a custom node was not checked.

A visit that waits while a game is saved comes back without its work in progress, and the node’s Run runs again from the top, which is harmless for most nodes but not for one that holds a count or a choice that running it again cannot rebuild. For those, implement ISavableNode.

Member What it does
StateVersion The version of the state. Raise it when its meaning changes.
SaveState(NodeInfo flow) Returns the text to save, or null. Asked when a save is made while a visit of the node waits.
RestoreState(NodeInfo flow, string state, int version) Gives a restored visit its state back before the run goes on.

One node object serves every run of the scheme, so per-visit state must never live in instance fields. The state is text of at most 4096 characters. A longer state, or a SaveState that throws, is left out of the save with a warning, and the visit is still saved.

This node waits a number of frames and remembers how many it has waited. The count belongs to one visit. The node object is shared by every run of the scheme, and visit IDs repeat from one run to the next, so the example keeps the count in a table keyed by the visit object (NodeInfo), never in a field or under flow.id. A count alone would also fit in flow.index, which the visit saves on its own; the table is here to show the interface. It counts frames, not game time, so it keeps counting while the scheme is paused.

Example. Compiled against the package’s runtime assembly; not run in Unity.

using System;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using MrW.Intrigues.Graph;
[Serializable]
[GraphNode("Frames Gate", "Flow/Frames Gate", NodeCategory.Flow,
Description = "Waits a number of frames, then goes on.",
AfterLoad = AfterLoadMode.Safe)]
public sealed class FramesGateData : NodeData, ISavableNode
{
[UnityEngine.Min(1)]
public int Frames = 120;
// Frames already waited, per visit. One node object serves every run of the scheme,
// so the count hangs on the visit object itself, never on a field or an ID.
private sealed class Count { public int Done; }
private static readonly ConditionalWeakTable<NodeInfo, Count> waited = new ConditionalWeakTable<NodeInfo, Count>();
public override void Describe(NodeDescription d) => d.Line($"Waits {Frames} frames");
public override async Task Run(NodeInfo flow)
{
flow.Begin();
var count = waited.GetValue(flow, _ => new Count());
while (count.Done < Frames)
{
await Task.Yield();
if (!flow.StillValid()) return;
count.Done++;
}
await flow.Next(0);
}
public int StateVersion => 1;
public string SaveState(NodeInfo flow) =>
waited.TryGetValue(flow, out var count) ? count.Done.ToString(CultureInfo.InvariantCulture) : null;
public void RestoreState(NodeInfo flow, string state, int version)
{
if (int.TryParse(state, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value))
waited.GetValue(flow, _ => new Count()).Done = value;
}
}

After an await on real work, flow.StillValid() tells you whether the scheme’s requirements still hold. Return at once when it says no. When a number is all you need to keep, reach first for the fields that NodeInfo already saves on its own, which are time, index, repeatCount and indexes, because they cost you no state code at all. A node that repeats something it did before it waited should say AfterLoad = AfterLoadMode.RunsAgain, and the Studio then shows a badge on the card.

What you see Why What to do
The node is not in the Add Node window, and the Console says it has no [GraphNode] attribute. The attribute is missing. Add it.
A scheme never ends after your node. A path of Run calls none of Next, End or Stop. End every path.
Nodes of your type vanished after a refactor. The class was renamed. Rename it back.