TExcelTAD
Home › Unreal Engine 5 with C++ › Behavior Trees & Blackboard

Behavior Trees & Blackboard

A Behavior Tree (BT) describes an AI's decisions as a tree of small nodes. Unreal's BT editor is visual, but most custom nodes are written in C++. The tree works with a Blackboard: a typed key/value store (TargetActor : Object, LastKnownLocation : Vector, bHasLowHealth : Bool) that perception, services and gameplay code write and the tree reads.

Node types

Node Role Built-in examples
Composite: Selector runs children left to right until one succeeds ("try options in priority order")
Composite: Sequence runs children left to right until one fails ("do these steps in order")
Composite: Simple Parallel a main task plus a background subtree
Task (leaf) does something; returns Succeeded, Failed or InProgress Move To, Wait, Play Animation, Run EQS Query
Decorator (on a node) a condition that gates the node, and can abort running branches Blackboard (is set / compare), Cooldown, Loop, Time Limit
Service (on a composite) runs at an interval while its branch is active, updating the blackboard Default Focus

Unreal's BTs are event-driven: they don't re-evaluate the whole tree every frame. A running task keeps running until it finishes, unless a decorator with an Observer Aborts setting sees its blackboard key change. Lower Priority aborts branches to the right of it (lower priority) when its condition becomes true; Self aborts its own branch when the condition becomes false; Both does both.

A typical enemy tree:

text
Root
└─ Selector
   ├─ [Decorator: TargetActor Is Set, aborts Both]  Sequence "Attack"
   │     ├─ Move To (TargetActor, acceptance 150)
   │     └─ BTTask_ArenaAttack
   ├─ [Decorator: LastKnownLocation Is Set, aborts Both]  Sequence "Investigate"
   │     ├─ Move To (LastKnownLocation)
   │     ├─ Wait 2 s
   │     └─ BTTask_ClearKey (LastKnownLocation)
   └─ Sequence "Patrol"   [Service: BTService_PickPatrolPoint, every 0.5 s]
         ├─ Move To (PatrolPoint)
         └─ Wait 1 s

A C++ task

cpp
// BTTask_ArenaAttack.h
#pragma once

#include "CoreMinimal.h"
#include "BehaviorTree/Tasks/BTTask_BlackboardBase.h"
#include "BTTask_ArenaAttack.generated.h"

UCLASS()
class ARENA_API UBTTask_ArenaAttack : public UBTTask_BlackboardBase
{
    GENERATED_BODY()

public:
    UBTTask_ArenaAttack();

protected:
    virtual EBTNodeResult::Type ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory) override;
    virtual void TickTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory, float DeltaSeconds) override;

    UPROPERTY(EditAnywhere, Category = "Attack")
    float AttackRange = 200.f;
};
cpp
// BTTask_ArenaAttack.cpp
#include "BTTask_ArenaAttack.h"
#include "AIController.h"
#include "ArenaEnemy.h"
#include "BehaviorTree/BlackboardComponent.h"

UBTTask_ArenaAttack::UBTTask_ArenaAttack()
{
    NodeName = TEXT("Arena Attack");
    bNotifyTick = true;                                   // we finish later, in TickTask
    BlackboardKey.AddObjectFilter(this, GET_MEMBER_NAME_CHECKED(UBTTask_ArenaAttack, BlackboardKey), AActor::StaticClass());
}

EBTNodeResult::Type UBTTask_ArenaAttack::ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory)
{
    AAIController* AI = OwnerComp.GetAIOwner();
    AArenaEnemy* Enemy = AI ? Cast<AArenaEnemy>(AI->GetPawn()) : nullptr;
    AActor* Target = Cast<AActor>(OwnerComp.GetBlackboardComponent()->GetValueAsObject(BlackboardKey.SelectedKeyName));
    if (!Enemy || !IsValid(Target)) return EBTNodeResult::Failed;
    if (Enemy->GetDistanceTo(Target) > AttackRange) return EBTNodeResult::Failed;

    Enemy->StartAttack(Target);                            // plays a montage
    return EBTNodeResult::InProgress;                      // latent: finish when the attack ends
}

void UBTTask_ArenaAttack::TickTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory, float DeltaSeconds)
{
    const AArenaEnemy* Enemy = Cast<AArenaEnemy>(OwnerComp.GetAIOwner()->GetPawn());
    if (!Enemy || !Enemy->IsAttacking())
    {
        FinishLatentTask(OwnerComp, EBTNodeResult::Succeeded);
    }
}

Notes:

  • Node instances are shared. By default one task object serves every AI running the tree, so a member variable written in ExecuteTask is shared by all of them. Per-AI state goes into node memory (override GetInstanceMemorySize() and use a struct in NodeMemory), or set bCreateNodeInstance = true (simpler, costs an object per AI).
  • Instead of polling in TickTask, a task can finish from a delegate (the montage-ended callback) by calling FinishLatentTask. Override AbortTask to stop the montage when a decorator aborts the branch.
  • Blueprint tasks (BTTask_BlueprintBase) are fine for prototypes and designer tweaks; hot tasks belong in C++.

A runnable behavior-tree model

The model has a selector of three sequences, blackboard decorators with observer aborts, and a latent Move task that takes several ticks. Perception events write to the blackboard between ticks, and the output shows the tree reacting: patrol, chase when the player is seen, abort the chase when sight is lost, and investigate the last known location.

cpp · try it yourself
#include <functional>
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <vector>

enum class Status { Success, Failure, Running };
using Blackboard = std::map<std::string, int>;            // 0 = not set

struct Node {
    std::string Name;
    virtual ~Node() = default;
    virtual Status Tick(Blackboard& bb) = 0;
    virtual void Abort() {}
};

struct Task : Node {                                       // latent task: runs for N ticks
    int Duration, Left = 0;
    std::function<void(Blackboard&)> OnDone;
    Task(std::string n, int d, std::function<void(Blackboard&)> f = nullptr) : Duration(d), OnDone(f) { Name = n; }
    Status Tick(Blackboard& bb) override {
        if (Left == 0) Left = Duration;
        if (--Left > 0) { std::cout << " " << Name << "(running)"; return Status::Running; }
        std::cout << " " << Name << "(done)";
        if (OnDone) OnDone(bb);
        return Status::Success;
    }
    void Abort() override { Left = 0; }
};

struct Sequence : Node {
    std::string Key;                                       // decorator: "Key is set" (empty = none)
    std::vector<std::unique_ptr<Node>> Kids;
    size_t Current = 0;
    bool Pass(const Blackboard& bb) const { return Key.empty() || bb.count(Key) && bb.at(Key) != 0; }
    Status Tick(Blackboard& bb) override {
        while (Current < Kids.size()) {
            Status s = Kids[Current]->Tick(bb);
            if (s == Status::Running) return s;
            if (s == Status::Failure) { Current = 0; return s; }
            Current++;
        }
        Current = 0;
        return Status::Success;
    }
    void Abort() override { for (auto& k : Kids) k->Abort(); Current = 0; }
};

struct Selector : Node {
    std::vector<std::unique_ptr<Sequence>> Kids;
    int Running = -1;
    Status Tick(Blackboard& bb) override {
        // Observer aborts (Both): a higher-priority branch whose decorator passes preempts the running one,
        // and the running one is aborted if its own decorator fails.
        for (int i = 0; i < (int)Kids.size(); i++) {
            if (!Kids[i]->Pass(bb)) continue;
            if (Running != -1 && Running != i) {
                std::cout << " [abort " << Kids[Running]->Name << "]";
                Kids[Running]->Abort();
            }
            Running = i;
            std::cout << " " << Kids[i]->Name << ":";
            Status s = Kids[i]->Tick(bb);
            if (s != Status::Running) Running = -1;
            return s;
        }
        return Status::Failure;
    }
};

std::unique_ptr<Sequence> Seq(std::string name, std::string key, std::vector<Node*> kids) {
    auto s = std::make_unique<Sequence>();
    s->Name = name; s->Key = key;
    for (Node* k : kids) s->Kids.emplace_back(k);
    return s;
}

int main() {
    Blackboard bb;
    Selector root;
    root.Kids.push_back(Seq("Attack", "Target", {new Task("MoveToTarget", 4), new Task("Attack", 1)}));
    root.Kids.push_back(Seq("Investigate", "LastKnown", {new Task("MoveToLastKnown", 2), new Task("Wait", 1),
                                                          new Task("ClearLastKnown", 1, [](Blackboard& b) { b["LastKnown"] = 0; })}));
    root.Kids.push_back(Seq("Patrol", "", {new Task("MoveToPatrolPoint", 3), new Task("Wait", 1)}));

    std::map<int, std::string> events = {{3, "player seen"}, {5, "player lost"}};
    for (int tick = 1; tick <= 10; tick++) {
        if (events.count(tick)) {
            std::cout << "-- perception: " << events[tick] << "\n";
            if (events[tick] == "player seen") bb["Target"] = 1;
            else { bb["Target"] = 0; bb["LastKnown"] = 1; }
        }
        std::cout << "tick " << tick << ":";
        root.Tick(bb);
        std::cout << "\n";
    }
}
tick 1: Patrol: MoveToPatrolPoint(running)
tick 2: Patrol: MoveToPatrolPoint(running)
-- perception: player seen
tick 3: [abort Patrol] Attack: MoveToTarget(running)
tick 4: Attack: MoveToTarget(running)
-- perception: player lost
tick 5: [abort Attack] Investigate: MoveToLastKnown(running)
tick 6: Investigate: MoveToLastKnown(done) Wait(done) ClearLastKnown(done)
tick 7: Patrol: MoveToPatrolPoint(running)
tick 8: Patrol: MoveToPatrolPoint(running)
tick 9: Patrol: MoveToPatrolPoint(done) Wait(done)
tick 10: Patrol: MoveToPatrolPoint(running)

The patrol move was aborted the moment the target appeared (a Lower Priority abort), the chase was aborted when the target was lost (a Self abort), and after investigating the AI cleared the key and fell back to patrolling.

Test yourself

What does a Selector do?

  1. Runs all children at once
  2. Runs children in order until one succeeds
  3. Runs children in order until one fails
  4. Picks a random child

A patrol is running when the player is spotted. What makes the tree switch to the attack branch immediately?

  1. A service
  2. A decorator on the attack branch with Observer Aborts set to Lower Priority (or Both)
  3. A Wait task
  4. Restarting the tree

Why shouldn't a BT task store per-AI state in a member variable by default?

  1. Members can't be UPROPERTYs
  2. Task node instances are shared by every AI running the tree, unless bCreateNodeInstance is set
  3. Members are reset every tick
  4. It breaks replication