TExcelTAD
Home › Game AI › Unreal: AIController, Behavior Trees & Blackboard

Unreal: AIController, Behavior Trees & Blackboard

Unreal Engine 5 has the most complete built-in AI framework of the three big engines. Its pieces map directly onto this course:

Unreal Course concept
AAIController the "brain" that possesses a pawn: sense, think, act (Sense, Think, Act)
Behavior Tree asset (UBehaviorTree) Behavior Trees
Blackboard asset + UBlackboardComponent The Blackboard
Tasks, Decorators, Services leaves, conditions, periodic updates (Decorators, Running & Aborts)
Navigation System + Recast navmesh Navigation Meshes
EQS, StateTree, AI Perception the next lesson

The controller

A pawn's AI Controller Class (in its Class Defaults, together with Auto Possess AI) decides which controller takes it over. The controller starts the tree when it possesses the pawn:

cpp
// GuardAIController.h
#pragma once
#include "AIController.h"
#include "GuardAIController.generated.h"

UCLASS()
class AGuardAIController : public AAIController
{
    GENERATED_BODY()
protected:
    UPROPERTY(EditDefaultsOnly, Category = "AI")
    TObjectPtr<UBehaviorTree> GuardTree;

    virtual void OnPossess(APawn* InPawn) override;
};

// GuardAIController.cpp
#include "GuardAIController.h"
#include "BehaviorTree/BehaviorTree.h"

void AGuardAIController::OnPossess(APawn* InPawn)
{
    Super::OnPossess(InPawn);
    if (GuardTree)
    {
        RunBehaviorTree(GuardTree);   // also initializes the tree's Blackboard asset
    }
}

RunBehaviorTree creates the blackboard component from the tree's Blackboard asset. Other code then talks to the AI through the blackboard, not by calling into the tree:

cpp
if (UBlackboardComponent* BB = GetBlackboardComponent())
{
    BB->SetValueAsObject(TEXT("TargetActor"), SeenActor);
    BB->SetValueAsVector(TEXT("LastKnownLocation"), SeenActor->GetActorLocation());
    BB->SetValueAsBool(TEXT("IsAlerted"), true);
}

For movement outside a tree, MoveToActor(Goal, AcceptanceRadius) and MoveToLocation(Dest, AcceptanceRadius) request a path on the navmesh, and overriding OnMoveCompleted tells you how it ended. Inside a tree, the built-in Move To task does the same thing for a blackboard key.

Tasks, decorators and services

  • Composites: Selector (first child that succeeds), Sequence (all children in order), Simple Parallel (one main task plus a background branch).
  • Tasks are the leaves. A C++ task overrides ExecuteTask and returns EBTNodeResult::Succeeded, Failed, or InProgress for work that takes several frames. A latent task finishes later by calling FinishLatentTask.
  • Decorators are conditions attached to a node ("Blackboard: TargetActor Is Set", "Cooldown", "Loop").
  • Services run at an interval while their branch is active, typically to update blackboard keys (pick the nearest enemy every 0.5 s).

A latent C++ task that searches the area for a few seconds:

cpp
// BTTask_LookAround.h
#pragma once
#include "BehaviorTree/BTTaskNode.h"
#include "BTTask_LookAround.generated.h"

UCLASS()
class UBTTask_LookAround : public UBTTaskNode
{
    GENERATED_BODY()
public:
    UBTTask_LookAround();
    UPROPERTY(EditAnywhere, Category = "AI")
    float Duration = 3.f;

protected:
    virtual EBTNodeResult::Type ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory) override;
    virtual void TickTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory, float DeltaSeconds) override;
    virtual uint16 GetInstanceMemorySize() const override { return sizeof(float); }
};

// BTTask_LookAround.cpp
UBTTask_LookAround::UBTTask_LookAround()
{
    NodeName = TEXT("Look Around");
    bNotifyTick = true;                               // we want TickTask calls
}

EBTNodeResult::Type UBTTask_LookAround::ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory)
{
    *reinterpret_cast<float*>(NodeMemory) = Duration;  // per-AI state lives in node memory
    return EBTNodeResult::InProgress;
}

void UBTTask_LookAround::TickTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory, float DeltaSeconds)
{
    float& Remaining = *reinterpret_cast<float*>(NodeMemory);
    if (APawn* Pawn = OwnerComp.GetAIOwner()->GetPawn())
    {
        Pawn->AddActorWorldRotation(FRotator(0.f, 90.f * DeltaSeconds, 0.f));
    }
    Remaining -= DeltaSeconds;
    if (Remaining <= 0.f)
    {
        FinishLatentTask(OwnerComp, EBTNodeResult::Succeeded);
    }
}

Note: Behavior tree nodes are shared by every AI running the same tree (they aren't instanced per AI by default), so per-AI state goes in node memory (GetInstanceMemorySize) or the blackboard, never in member variables that change at runtime. Blueprint tasks (BTTask_BlueprintBase) are instanced, which is simpler but costs more.

Event-driven trees and observer aborts

A textbook behavior tree re-evaluates from the root every tick. Unreal's trees are event-driven: once a task is running, the tree just waits for it. Conditions are re-checked only when something they observe changes. That's what a decorator's Observer aborts setting controls:

Observer aborts When the observed value changes…
None nothing happens; the running task continues
Self if the condition fails, abort this branch
Lower Priority if the condition passes, abort branches to the right of this one
Both both of the above

This model has a root Selector with two branches: Chase (behind a "Has TargetActor" decorator) and Patrol. Perception sets TargetActor on tick 1 and clears it on tick 6. Composites remember their running child, so nothing but an observer abort can interrupt a task:

csharp · try it yourself
using System;
using System.Collections.Generic;

foreach (var mode in new[] { Aborts.None, Aborts.Both })
{
    Console.WriteLine(
quot;Observer aborts: {mode}"); var bb = new Blackboard(); var chase = new Sequence(new Latent("MoveTo(TargetActor)", 2), new Latent("Attack", 2)); var patrol = new Sequence(new Latent("MoveTo(PatrolPoint)", 3), new Latent("Wait", 2)); var hasTarget = new BlackboardDecorator("TargetActor", chase, mode); var root = new Selector(hasTarget, patrol); for (int tick = 0; tick < 12; tick++) { string note = ""; if (tick == 1) note = bb.Set("TargetActor", "Player", hasTarget, root); if (tick == 6) note = bb.Set("TargetActor", null, hasTarget, root); root.Tick(bb); Console.WriteLine(
quot; tick {tick,2}: {note}{Latent.LastRun}"); } } enum Status { Succeeded, Failed, InProgress } enum Aborts { None, Self, LowerPriority, Both } class Blackboard { readonly Dictionary<string, object?> values = new(); public object? Get(string key) => values.TryGetValue(key, out var v) ? v : null; // Setting a key notifies the decorator observing it (Unreal does this with observers). public string Set(string key, object? value, BlackboardDecorator observer, Node root) { values[key] = value; bool pass = value != null; bool self = observer.Mode is Aborts.Self or Aborts.Both; bool lower = observer.Mode is Aborts.LowerPriority or Aborts.Both; if (observer.Active && !pass && self) { root.Abort(); return "[abort Self] "; } if (!observer.Active && pass && lower) { root.Abort(); return "[abort Lower Priority] "; } return ""; } } abstract class Node { public abstract Status Tick(Blackboard bb); public virtual void Abort() { } } class Latent : Node { public static string LastRun = ""; readonly string name; readonly int ticks; int left = -1; public Latent(string name, int ticks) { this.name = name; this.ticks = ticks; } public override Status Tick(Blackboard bb) { if (left < 0) left = ticks; // ExecuteTask left--; // TickTask var s = left > 0 ? Status.InProgress : Status.Succeeded; if (s == Status.Succeeded) left = -1; // FinishLatentTask LastRun =
quot;{name} {s}"; return s; } public override void Abort() => left = -1; } class Sequence : Node { readonly Node[] kids; int i; public Sequence(params Node[] kids) => this.kids = kids; public override Status Tick(Blackboard bb) { while (i < kids.Length) { var s = kids[i].Tick(bb); if (s == Status.InProgress) return s; if (s == Status.Failed) { i = 0; return s; } i++; } i = 0; return Status.Succeeded; } public override void Abort() { foreach (var k in kids) k.Abort(); i = 0; } } class Selector : Node { readonly Node[] kids; int i; public Selector(params Node[] kids) => this.kids = kids; public override Status Tick(Blackboard bb) { while (i < kids.Length) { var s = kids[i].Tick(bb); if (s == Status.InProgress) return s; if (s == Status.Succeeded) { i = 0; return s; } i++; } i = 0; return Status.Failed; } public override void Abort() { foreach (var k in kids) k.Abort(); i = 0; } } class BlackboardDecorator : Node { readonly string key; readonly Node child; public readonly Aborts Mode; public bool Active; public BlackboardDecorator(string key, Node child, Aborts mode) { this.key = key; this.child = child; Mode = mode; } public override Status Tick(Blackboard bb) { if (!Active && bb.Get(key) == null) return Status.Failed; // checked only on entry var s = child.Tick(bb); Active = s == Status.InProgress; return s; } public override void Abort() { child.Abort(); Active = false; } }
Observer aborts: None
  tick  0: MoveTo(PatrolPoint) InProgress
  tick  1: MoveTo(PatrolPoint) InProgress
  tick  2: Wait InProgress
  tick  3: Wait Succeeded
  tick  4: MoveTo(TargetActor) InProgress
  tick  5: Attack InProgress
  tick  6: Attack Succeeded
  tick  7: MoveTo(PatrolPoint) InProgress
  tick  8: MoveTo(PatrolPoint) InProgress
  tick  9: Wait InProgress
  tick 10: Wait Succeeded
  tick 11: MoveTo(PatrolPoint) InProgress
Observer aborts: Both
  tick  0: MoveTo(PatrolPoint) InProgress
  tick  1: [abort Lower Priority] MoveTo(TargetActor) InProgress
  tick  2: Attack InProgress
  tick  3: Attack Succeeded
  tick  4: MoveTo(TargetActor) InProgress
  tick  5: Attack InProgress
  tick  6: [abort Self] MoveTo(PatrolPoint) InProgress
  tick  7: MoveTo(PatrolPoint) InProgress
  tick  8: Wait InProgress
  tick  9: Wait Succeeded
  tick 10: MoveTo(PatrolPoint) InProgress
  tick 11: MoveTo(PatrolPoint) InProgress

With None, the guard finishes its patrol leg and its wait (ticks 1–3) before it even looks at the new target, and on tick 6 it still finishes an attack on a player it has already lost. With Both, the guard switches the moment the key changes in either direction. That's why a "Has target" decorator in front of a chase branch is almost always set to Both (or Lower Priority plus a Self-aborting check inside).

Debugging

Press the apostrophe (') key in Play In Editor to open the Gameplay Debugger. The numpad keys toggle categories such as the behavior tree, EQS, navmesh and perception for the AI in front of the camera. The behavior tree editor also highlights the active branch live while the game runs, and you can set breakpoints on nodes. More in Debugging AI and Unreal Engine 5 with C++.

Test yourself

Where should a C++ behavior tree task keep a per-AI countdown?

  1. In a member variable of the task class
  2. In node memory (GetInstanceMemorySize) or the blackboard
  3. In a static variable
  4. In the AIController's constructor

A Patrol task is running. Perception sets TargetActor, and a higher-priority Chase branch is guarded by "TargetActor Is Set". Which Observer aborts setting makes Chase start immediately?

  1. None
  2. Self
  3. Lower Priority (or Both)
  4. Any setting: the tree re-checks every tick

What does a task return from ExecuteTask when its work takes several frames?

  1. EBTNodeResult::Succeeded
  2. EBTNodeResult::InProgress, then later FinishLatentTask
  3. EBTNodeResult::Aborted
  4. Nothing; it blocks until done