Event-driven trees

Stop ticking the whole tree every frame: tick it only when something it depends on changes, let long actions run on their own and report back, and abort a running branch when a higher-priority condition becomes true.

A reactive tree (from Reactive versus memory nodes) starts again from its root on every tick, and most games tick it every frame. That is simple and always up to date, and most of the work is wasted. A watchman who walks the wall for a minute is ticked 3,600 times at 60 frames a second, and each tick asks “is an intruder in sight?” and “is the alarm ringing?” and gets the same two answers it got the frame before. Multiply by fifty guards and the tree spends its time confirming that nothing happened.

An event-driven tree is ticked only when something it depends on has changed. Between those moments it does nothing, and the action that is running carries on by itself. It decides the same things a tree ticked every frame decides, as long as every change that could alter a decision arrives as an event. Unreal’s behavior trees work this way, and it is the main reason they look different from the trees in most tutorials.

Three ideas an event-driven tree needs

An event is a message that something changed: the alarm started ringing, an intruder came into view, an action finished. An event-driven runtime needs three things to turn events into decisions.

A blackboard that announces changes. The blackboard is the tree’s shared memory: named variables, such as intruder_seen or alarm_ringing, that the game writes and the tree’s conditions read. In an event-driven tree, setting a variable to a new value raises a change event, and setting it to the value it already has raises nothing. Conditions read the blackboard instead of asking the world directly, so every change they could notice passes through one place that can announce it.

Actions that report when they finish. In the trees of the earlier pages, an action makes progress only while it is ticked: it checks each frame whether the watchman has arrived. In an event-driven tree, a latent action starts its work on its first tick (it asks the navigation system to walk to the beacon) and returns Running; the work then continues in the game, and when it ends the action raises a “finished” event that wakes the tree. Unreal calls this a latent task, and BehaviorTree.CPP an asynchronous action.

Aborts. When a change wakes the tree and a higher-priority branch now applies, the action that was running must be stopped: the watchman stops walking the wall before he runs to the beacon. To abort a running node is to stop it and let it undo what it started, such as stopping the walk. This is the same halting that Concurrency covers for a parallel node; here the cause is an event instead of a sibling finishing. Unreal attaches it to the condition: a decorator that reads a blackboard key observes it, and its “observer aborts” setting says whose branch a change cancels: its own branch (self), the branches to its right that it outranks (lower priority), or both.

A tree you can run

The watchman walks the wall. When the alarm rings he runs to the beacon, and when he sees an intruder he chases it, which outranks everything else. The two conditions read the blackboard, and each custom node says which variable it reads under blackboard_reads. That list is what an event-driven runtime subscribes to: it is the set of changes that could alter a decision.

version: "1.0"
metadata:
  name: watchman
  description: "Walks the wall, runs to the beacon when the alarm rings and chases an intruder he sees; what he checks changes a few times a minute, not every frame"
  tags: [event-driven]
blackboard:
  - {name: intruder_seen, type: bool, default: false, description: "Set by the watchman's sight when an intruder comes into view or leaves it"}
  - {name: alarm_ringing, type: bool, default: false, description: "Set by the bell tower when the alarm starts or stops"}
custom_nodes:
  - name: IntruderSeen
    type: condition
    description: "Succeeds while an intruder is in sight"
    blackboard_reads: [intruder_seen]
  - name: AlarmRinging
    type: condition
    description: "Succeeds while the alarm bell rings"
    blackboard_reads: [alarm_ringing]
  - name: MoveTo
    type: action
    description: "Walks to a named place; Running until he arrives"
    parameters:
      - {name: target, type: string}
tree:
  type: selector
  name: watchman_root
  children:
    - type: sequence
      name: chase_intruder
      children:
        - {type: condition, name: intruder_in_sight, node: IntruderSeen}
        - {type: action, name: run_at_intruder, node: MoveTo, parameters: {target: intruder}}
    - type: sequence
      name: answer_alarm
      children:
        - {type: condition, name: alarm_heard, node: AlarmRinging}
        - {type: action, name: run_to_beacon, node: MoveTo, parameters: {target: beacon}}
    - {type: action, name: walk_the_wall, node: MoveTo, parameters: {target: wall_route}}

Save it as watchman.beetree.yaml. The root is a selector (a Fallback, from Building blocks), so its branches are in priority order: chasing outranks the alarm, and the alarm outranks the wall.

On a quiet night, neither condition holds and the watchman walks the wall:

beetree simulate watchman.beetree.yaml --override intruder_in_sight=FAILURE --override alarm_heard=FAILURE --override walk_the_wall=RUNNING
Simulation: watchman_root → RUNNING
──────────────────────────────────────────────────
▶ ? watchman_root
  ▶ → chase_intruder
    ● ¿ intruder_in_sight → FAILURE
  ◀ → chase_intruder → FAILURE
  ▶ → answer_alarm
    ● ¿ alarm_heard → FAILURE
  ◀ → answer_alarm → FAILURE
  ● ! walk_the_wall → RUNNING
◀ ? watchman_root → RUNNING

This is the tick an event-driven runtime runs once, and then sleeps. The tree is now waiting on three things: a change to intruder_seen, a change to alarm_ringing, and walk_the_wall finishing. Nothing else can change what it decides, so a tick on any other frame would print exactly these lines again.

When the bell tower sets alarm_ringing to true, the change event wakes the tree, and it ticks once more:

beetree simulate watchman.beetree.yaml --override intruder_in_sight=FAILURE --override alarm_heard=SUCCESS --override run_to_beacon=RUNNING
Simulation: watchman_root → RUNNING
──────────────────────────────────────────────────
▶ ? watchman_root
  ▶ → chase_intruder
    ● ¿ intruder_in_sight → FAILURE
  ◀ → chase_intruder → FAILURE
  ▶ → answer_alarm
    ● ¿ alarm_heard → SUCCESS
    ● ! run_to_beacon → RUNNING
  ◀ → answer_alarm → RUNNING
◀ ? watchman_root → RUNNING

walk_the_wall was running on the last tick and was not reached on this one, so the runtime aborts it before run_to_beacon starts: the watchman stops walking the wall and turns toward the beacon. Over a quiet minute with one alarm, the tree ran two ticks instead of 3,600, and decided exactly what a tree ticked every frame would have.

What can go wrong

An event-driven tree is only as right as its events. Three mistakes account for most of the bugs:

  • A condition that reads something with no event. If IntruderSeen asked the physics engine directly instead of reading intruder_seen, nothing would wake the tree when an intruder appeared, and the watchman would keep walking. Every input a condition reads must be a blackboard variable that something sets, and blackboard_reads should name all of them.
  • Values that change continuously. A distance to a target changes every frame, so an event per change saves nothing. Turn it into an event at the threshold that matters (target_in_range flips from false to true), or refresh it on a timer slower than the frame rate. Unreal’s services do the second: a node that runs at an interval while its branch is active and writes fresh values to the blackboard.
  • An abort that does not clean up. An aborted action must stop what it started: the navigation request, the animation, the sound. A runtime that forgets this leaves a watchman walking the wall and running to the beacon at once.

A middle way needs no events at all: tick the whole tree on a timer, five or ten times a second instead of sixty. It keeps the simplicity of a reactive tree, cuts most of the cost, and reacts a little later. Many games do this for characters far from the player.

Engine code

The samples add an event-driven runner to the Status, tick(), Sequence, Fallback and Condition from Building blocks. The Blackboard raises a change event only when a value really changes. A LatentAction starts its work on its first tick, reports back with Finish, and is stopped with Abort. The EventDrivenTree ticks the root only when a watched variable changed or an action finished, and after each tick aborts any action that was running before and was not reached this time. Call its Update every frame: on a frame with no event it returns at once.

Agnostic

Blackboard:
    set(key, value):
        if values[key] == value: return       // no change, no event
        values[key] = value
        emit changed(key)

LatentAction(start, stop):                    // runs in the game between ticks
    tick():
        ticked = true
        if result is set: running = false; return take(result)
        if not running: running = true; start(this)
        return Running
    finish(status): result = status; emit finished
    endTick():                                // after every tick of the tree
        if running and not ticked: running = false; stop()   // abort
        ticked = false

EventDrivenTree(root, blackboard, watchedKeys, actions):
    dirty = true                              // tick once at the start
    on blackboard.changed(key): if key in watchedKeys: dirty = true
    on any action.finished: dirty = true
    update():                                 // call every frame
        if not dirty: return                  // nothing changed: no work
        dirty = false
        status = root.tick()
        for action in actions: action.endTick()
        if status is not Running: dirty = true   // finished: start again next frame

Unity C#

public class Blackboard
{
    readonly System.Collections.Generic.Dictionary<string, object> values =
        new System.Collections.Generic.Dictionary<string, object>();

    public event System.Action<string> Changed;

    public T Get<T>(string key, T fallback) =>
        values.TryGetValue(key, out var value) ? (T)value : fallback;

    public void Set(string key, object value)
    {
        if (values.TryGetValue(key, out var old) && Equals(old, value)) return; // no change, no event
        values[key] = value;
        Changed?.Invoke(key);
    }
}

// Starts its work on the first tick; the game calls Finish when the work ends.
public class LatentAction : Node
{
    readonly System.Action<LatentAction> start;
    readonly System.Action stop;
    bool running, ticked;
    Status? result;

    public event System.Action Finished;

    public LatentAction(System.Action<LatentAction> start, System.Action stop)
    {
        this.start = start;
        this.stop = stop;
    }

    public override Status Tick()
    {
        ticked = true;
        if (result is Status done)
        {
            result = null;
            running = false;
            return done;
        }
        if (!running)
        {
            running = true;
            start(this);
        }
        return Status.Running;
    }

    public void Finish(Status status)
    {
        result = status;
        Finished?.Invoke();
    }

    // After each tick of the tree: abort this action if it was running and the tick did not reach it.
    public void EndTick()
    {
        if (running && !ticked)
        {
            running = false;
            result = null;
            stop();
        }
        ticked = false;
    }
}

public class EventDrivenTree
{
    readonly Node root;
    readonly LatentAction[] actions;
    bool dirty = true; // tick once at the start
    public int Ticks { get; private set; }

    public EventDrivenTree(Node root, Blackboard blackboard, string[] watched, params LatentAction[] actions)
    {
        this.root = root;
        this.actions = actions;
        var keys = new System.Collections.Generic.HashSet<string>(watched);
        blackboard.Changed += key => { if (keys.Contains(key)) dirty = true; };
        foreach (var action in actions) action.Finished += () => dirty = true;
    }

    // Call from Update(): on a frame with no event it does nothing.
    public void Update()
    {
        if (!dirty) return;
        dirty = false;
        Ticks++;
        var status = root.Tick();
        foreach (var action in actions) action.EndTick();
        if (status != Status.Running) dirty = true; // finished: start again next frame
    }
}

public static class Watchman
{
    // moveTo starts walking to a place and calls Finish on the action when he arrives; stopMoving stops him.
    public static EventDrivenTree Build(Blackboard blackboard,
        System.Action<string, LatentAction> moveTo, System.Action stopMoving)
    {
        LatentAction MoveTo(string place) => new LatentAction(action => moveTo(place, action), stopMoving);
        var chase = MoveTo("intruder");
        var beacon = MoveTo("beacon");
        var wall = MoveTo("wall_route");
        var root = new Fallback(
            new Sequence(new ConditionNode(() => blackboard.Get("intruder_seen", false)), chase),
            new Sequence(new ConditionNode(() => blackboard.Get("alarm_ringing", false)), beacon),
            wall);
        return new EventDrivenTree(root, blackboard, new[] { "intruder_seen", "alarm_ringing" }, chase, beacon, wall);
    }
}

GDScript

class Blackboard:
    signal changed(key: String)
    var values := {}

    func get_value(key: String, fallback: Variant = null) -> Variant:
        return values.get(key, fallback)

    func set_value(key: String, value: Variant) -> void:
        if values.has(key) and values[key] == value:
            return   # no change, no event
        values[key] = value
        changed.emit(key)

# Starts its work on the first tick; the game calls finish() when the work ends.
class LatentAction extends BTNode:
    signal finished
    var start: Callable   # called with this action
    var stop: Callable
    var running := false
    var ticked := false
    var has_result := false
    var result: Status = Status.SUCCESS

    func _init(on_start: Callable, on_stop: Callable):
        start = on_start
        stop = on_stop

    func tick() -> Status:
        ticked = true
        if has_result:
            has_result = false
            running = false
            return result
        if not running:
            running = true
            start.call(self)
        return Status.RUNNING

    func finish(status: Status) -> void:
        result = status
        has_result = true
        finished.emit()

    # After each tick of the tree: abort this action if it was running and the tick did not reach it.
    func end_tick() -> void:
        if running and not ticked:
            running = false
            has_result = false
            stop.call()
        ticked = false

class BlackboardCondition extends BTNode:
    var blackboard: Blackboard
    var key: String

    func _init(b: Blackboard, k: String):
        blackboard = b
        key = k

    func tick() -> Status:
        return Status.SUCCESS if blackboard.get_value(key, false) else Status.FAILURE

class EventDrivenTree:
    var root: BTNode
    var watched: Array[String]
    var actions: Array[LatentAction]
    var dirty := true   # tick once at the start
    var ticks := 0

    func _init(r: BTNode, blackboard: Blackboard, w: Array[String], a: Array[LatentAction]):
        root = r
        watched = w
        actions = a
        blackboard.changed.connect(_on_changed)
        for action in actions:
            action.finished.connect(_on_finished)

    func _on_changed(key: String) -> void:
        if watched.has(key):
            dirty = true

    func _on_finished() -> void:
        dirty = true

    # Call from _process(): on a frame with no event it does nothing.
    func update() -> void:
        if not dirty:
            return
        dirty = false
        ticks += 1
        var status := root.tick()
        for action in actions:
            action.end_tick()
        if status != BTNode.Status.RUNNING:
            dirty = true   # finished: start again next frame

Unreal C++

class FBlackboard
{
public:
    TArray<TFunction<void(const FString&)>> Listeners; // called with the key that changed

    bool GetBool(const FString& Key) const
    {
        const bool* Found = Values.Find(Key);
        return Found ? *Found : false;
    }

    void SetBool(const FString& Key, bool Value)
    {
        const bool* Old = Values.Find(Key);
        if (Old && *Old == Value) return; // no change, no event
        Values.Add(Key, Value);
        for (const TFunction<void(const FString&)>& Listener : Listeners) Listener(Key);
    }

private:
    TMap<FString, bool> Values;
};

// Starts its work on the first tick; the game calls Finish when the work ends.
class FLatentAction : public FNode
{
public:
    TFunction<void(FLatentAction&)> Start;
    TFunction<void()> Stop;
    TFunction<void()> OnFinished; // set by the tree that runs this action

    EStatus Tick() override
    {
        bTicked = true;
        if (bHasResult)
        {
            bHasResult = false;
            bRunning = false;
            return Result;
        }
        if (!bRunning)
        {
            bRunning = true;
            Start(*this);
        }
        return EStatus::Running;
    }

    void Finish(EStatus Status)
    {
        Result = Status;
        bHasResult = true;
        if (OnFinished) OnFinished();
    }

    // After each tick of the tree: abort this action if it was running and the tick did not reach it.
    void EndTick()
    {
        if (bRunning && !bTicked)
        {
            bRunning = false;
            bHasResult = false;
            Stop();
        }
        bTicked = false;
    }

private:
    bool bRunning = false;
    bool bTicked = false;
    bool bHasResult = false;
    EStatus Result = EStatus::Success;
};

class FEventDrivenTree
{
public:
    TSharedPtr<FNode> Root;
    TArray<TSharedPtr<FLatentAction>> Actions;
    int32 Ticks = 0;

    // Subscribes to the watched keys and to every action finishing.
    void Watch(FBlackboard& Blackboard, const TArray<FString>& Keys)
    {
        Watched = Keys;
        Blackboard.Listeners.Add([this](const FString& Key) {
            for (const FString& Watching : Watched)
            {
                if (Watching == Key) bDirty = true;
            }
        });
        for (const TSharedPtr<FLatentAction>& Action : Actions)
        {
            Action->OnFinished = [this] { bDirty = true; };
        }
    }

    // Call from TickComponent: on a frame with no event it does nothing.
    void Update()
    {
        if (!bDirty) return;
        bDirty = false;
        ++Ticks;
        const EStatus Status = Root->Tick();
        for (const TSharedPtr<FLatentAction>& Action : Actions) Action->EndTick();
        if (Status != EStatus::Running) bDirty = true; // finished: start again next frame
    }

private:
    TArray<FString> Watched;
    bool bDirty = true; // tick once at the start
};

The Unity sample builds the whole watchman with Watchman.Build; in Godot and Unreal, assemble the same shape with the Sequence and Fallback from Building blocks, a BlackboardCondition (Godot) or an FCondition that calls GetBool (Unreal) for each condition, and one latent action per MoveTo. Wherever the game learns something, write it to the blackboard: the watchman’s sight sets intruder_seen, the bell tower sets alarm_ringing, and the navigation system calls Finish(Success) on the action that asked it to walk.

To see the saving, count: Ticks after a quiet minute is 1 where a tree ticked every frame would show 3,600.

The samples keep one thing simple on purpose: any watched change ticks the whole tree from the root. Unreal goes further and re-checks only the decorator that observes the key, then restarts the tree at the branch that changed; that saves more work in a large tree, and gives the same answers.

What BeeTreeCraft shows today

  • blackboard and a custom node’s blackboard_reads are part of the tree format, so a tree file can say what each condition depends on, which is what an event-driven runtime subscribes to. beetree validate checks the blackboard’s types and defaults, but not yet that each key in blackboard_reads is a declared variable, so check those names by eye.
  • beetree simulate runs one tick and does not model events or aborts: each run above is one tick, with the conditions forced to the values they would read. Running a tree for several ticks is issue 460.
  • The code beetree generate writes for Godot, Unity and Unreal ticks the tree from the root; making it event-driven is the runner above, written in your game. Unreal’s own behavior trees are event-driven already.

Where it comes from

Champandard and Dunstan’s The Behavior Tree Starter Kit (Game AI Pro) builds a first runtime that ticks from the root and then an event-driven one with a scheduler and observers, and compares them. Epic’s Behavior Tree in Unreal Engine: Overview explains why Unreal’s trees are event-driven, with conditions as decorators that observe the blackboard, observer aborts and services. BehaviorTree.CPP: Asynchronous Actions covers actions that run between ticks and how they are halted. More reading is on the Resources page.

Next, open the Build hub, paste the watchman into the builder and use Step through to answer each condition as the blackboard would, then read Graph structures and blackboards to see the blackboard as a graph of who writes each value and who reads it.