Scale: many agents on one budget
A town of three hundred villagers cannot tick three hundred trees every frame. Share one definition, work out costly facts once for everyone, put cheap checks first, and spend a fixed budget of ticks where the player is looking.
One guard with a behavior tree costs almost nothing. Three hundred villagers, each ticking its own tree sixty times a second, can cost more than the rest of the frame. Scale is the set of habits that keep the cost of many agents flat: share what can be shared, work out a costly fact once instead of once per agent, and spend a fixed amount of time each frame on the agents that matter most.
Where the time goes
A tick (one pass from the root down, as Building blocks describes) costs the sum of the nodes it visits. Composites are cheap: they read a status and pick a child. The leaves are where the time goes, and conditions most of all, because they run on every tick: a condition that casts a ray, searches for a path or scans every enemy in the level is often the most expensive line in the game’s AI.
So the cost of a frame is roughly agents × ticks per second × nodes visited × cost per node. Each factor is a lever:
- Fewer nodes visited: order the tree so that cheap checks run first and costly ones only when the cheap ones pass.
- Cheaper nodes: work out a fact that many agents need once, and let each condition read it.
- Fewer ticks: tick distant or idle agents less often, and spread ticks across frames.
- Less per agent: share the tree’s definition, and keep only each agent’s own state per agent.
The event-driven trees page covers a fifth lever: not ticking at all until something the tree reads changes.
One definition, many agents
A tree has two kinds of data. The definition is the shape and the parameters written in the tree file: which node is the parent of which, and that player_near compares with 15 metres. It is the same for every villager. The instance is what one agent’s run needs: which child of a sequence is running, when a cooldown ends, the agent’s own blackboard. It differs from agent to agent.
Keeping the two apart lets a game load the definition once and give each agent only a small block of instance memory. This is the flyweight pattern. Unreal’s behavior tree works this way: one tree asset is shared by every controller that runs it, and each node keeps its per-agent state in a block of node memory the component owns. The simpler way, and the one the samples on these pages use, builds a whole copy of the tree for each agent, with the state inside the nodes. That is fine for dozens of agents and worth changing only when the copies show up in a memory or load-time profile.
Work it out once
A shared computation is a fact many agents need that does not depend on which agent asks: is the town under attack, where is the player, which doors are open. When each agent’s tree works it out for itself, the game pays for it once per agent. Instead, one system works it out once a frame and writes it where every tree can read it, and the condition in each tree becomes a read.
In a tree file, a custom node names the blackboard variable it reads under blackboard_reads, so a reader of the tree sees that TownAlarm reads town_alarm and does not search for threats itself. Unreal’s services are the engine’s own version: a node that runs at a set interval while its branch is active and writes results to the blackboard for the nodes below it. A squad blackboard goes one step further: a blackboard shared by a group, so the squad agrees on one target instead of each member choosing its own.
Budgeting ticks
The tick rate is how often an agent’s tree is ticked. It does not have to be every frame, and it does not have to be the same for every agent:
- Level of detail (LOD): agents the player can see up close tick every frame and run their full behavior; agents further away tick a few times a second; distant ones once a second and run a cheaper branch. The player cannot tell, because they cannot see the difference.
- Staggering: agents that tick five times a second are spread across frames, so a twelfth of them tick in each frame rather than all of them every twelfth frame. Without it, the frame time spikes in a regular beat.
- A frame budget: a fixed time each frame for AI, say one millisecond. A scheduler ticks agents in order of how overdue they are and stops when the budget is spent. The agents it did not reach are still due, so they are first in line next frame: no agent waits for ever, and the frame never runs long because of AI.
A lower tick rate has a price: an agent ticked once a second reacts up to a second late. That is why the level of detail follows the player’s view. A villager behind the player can be a second late; the one they are talking to cannot.
A tree you can run
The townsfolk tree is written for a town of hundreds. Its first branch reads an alarm the town raises once for everyone. Its second branch, the full behavior, starts with the cheapest check there is (a distance compared with a number), so the costly line-of-sight check runs only for the villagers near the player. Every other villager falls through to follow_schedule, which walks the day’s route without pathfinding or animation.
# file: townsfolk.beetree.yaml
version: "1.0"
metadata:
name: townsfolk
description: "One villager of hundreds: one shared alarm check, cheap checks before costly ones, and a cheap branch for villagers far from the player"
tags: [scale, level-of-detail, shared-computation]
blackboard:
- {name: town_alarm, type: bool, default: false, description: "Raised by the town once a frame for every villager: one threat check shared by all of them"}
- {name: player_distance, type: float, default: 100.0, description: "Metres to the player, written by the scheduler once a frame when it picks the villager's tick rate"}
custom_nodes:
- name: TownAlarm
type: condition
description: "Succeeds when the town's alarm is raised. Reads one shared value; it does not look for threats itself"
blackboard_reads: [town_alarm]
- name: Within
type: condition
description: "Succeeds when the player is closer than distance. A number compared with a number: the cheapest check there is"
parameters:
- {name: distance, type: float, default: 15.0}
blackboard_reads: [player_distance]
- name: PlayerInSight
type: condition
description: "Succeeds when a ray from the villager's eyes reaches the player: the costly check, so it runs only after Within"
- name: RunToShelter
type: action
description: "Paths to the nearest shelter"
- name: Greet
type: action
description: "Turns to the player, plays a greeting and a line of dialogue"
- name: WorkStall
type: action
description: "Works at the villager's market stall, with full animation"
- name: FollowSchedule
type: action
description: "Moves the villager along the day's schedule without pathfinding or animation: cheap enough for every villager the player cannot see up close"
tree:
type: selector
name: townsfolk_root
children:
- type: sequence
name: alarm
children:
- {type: condition, name: alarm_raised, node: TownAlarm}
- {type: action, name: run_to_shelter, node: RunToShelter}
- type: sequence
name: full_detail
children:
- {type: condition, name: player_near, node: Within, parameters: {distance: 15.0}}
- type: selector
name: near_life
children:
- type: sequence
name: greet_player
children:
- {type: condition, name: player_in_sight, node: PlayerInSight}
- {type: action, name: greet, node: Greet}
- {type: action, name: work_at_stall, node: WorkStall}
- {type: action, name: follow_schedule, node: FollowSchedule}
Check it, then run the three kinds of villager. First the one far from the player, which is nearly all of them:
beetree validate townsfolk.beetree.yaml
beetree simulate townsfolk.beetree.yaml --override alarm_raised=FAILURE --override player_near=FAILURE
Simulation: townsfolk_root → SUCCESS
──────────────────────────────────────────────────
▶ ? townsfolk_root
▶ → alarm
● ¿ alarm_raised → FAILURE
◀ → alarm → FAILURE
▶ → full_detail
● ¿ player_near → FAILURE
◀ → full_detail → FAILURE
● ! follow_schedule → SUCCESS
◀ ? townsfolk_root → SUCCESS
Count the leaves the trace shows (●): three, and two of them are a read of a value and a comparison of two numbers. The ray is never cast. That is the cost of a distant villager, and the tree’s order is what keeps it there.
Now a villager near the player, at its stall, with the player out of its sight:
beetree simulate townsfolk.beetree.yaml --override alarm_raised=FAILURE --override player_in_sight=FAILURE --override work_at_stall=RUNNING
Simulation: townsfolk_root → RUNNING
──────────────────────────────────────────────────
▶ ? townsfolk_root
▶ → alarm
● ¿ alarm_raised → FAILURE
◀ → alarm → FAILURE
▶ → full_detail
● ¿ player_near → SUCCESS
▶ ? near_life
▶ → greet_player
● ¿ player_in_sight → FAILURE
◀ → greet_player → FAILURE
● ! work_at_stall → RUNNING
◀ ? near_life → RUNNING
◀ → full_detail → RUNNING
◀ ? townsfolk_root → RUNNING
Four leaves, one of them the ray. Only the few villagers within 15 metres pay for it. Last, the alarm: every villager, near or far, reads the same value and runs for shelter, and nobody looks for the threat themselves:
beetree simulate townsfolk.beetree.yaml --override run_to_shelter=RUNNING
Simulation: townsfolk_root → RUNNING
──────────────────────────────────────────────────
▶ ? townsfolk_root
▶ → alarm
● ¿ alarm_raised → SUCCESS
● ! run_to_shelter → RUNNING
◀ → alarm → RUNNING
◀ ? townsfolk_root → RUNNING
Had PlayerInSight come before Within, every villager in the town would cast a ray on every tick to learn what a subtraction could have told it. Swap the two conditions and run the first command again to see the extra leaf in the trace.
Engine code
The samples build on the Node and Status of Building blocks. Each has three parts.
TickScheduler holds the agents and when each is next due. Each frame, Run ticks the agents that are due, most overdue first, and stops when the frame’s budget is spent; an agent it did not reach stays due and goes first next frame. Add staggers new agents across one interval, so a hundred agents added in one frame do not all tick in the same frame again. LodInterval is the level of detail: every frame within 15 metres of the player, five times a second within 50, once a second beyond.
OncePerFrame is the shared computation: it works a value out the first time it is asked in a frame and hands every later caller the same answer. The town’s alarm is one of these, and each villager’s TownAlarm condition reads it.
Agnostic
ScheduledAgent: root, interval, nextDue
TickScheduler:
add(agent, now):
agent.nextDue = now + agent.interval * (count % 10) / 10 // stagger
agents.add(agent)
run(now, budget): // once per frame
start = clock()
for agent in agents, sorted by nextDue: // most overdue first
if agent.nextDue > now: stop // nobody else is due
if clock() - start >= budget: stop // the rest wait for next frame
agent.root.tick()
agent.nextDue = now + agent.interval
lodInterval(distance) = 0 if distance < 15 // every frame
0.2 if distance < 50 // five times a second
1 otherwise // once a second
OncePerFrame(compute):
get(frame):
if frame != lastFrame: value = compute(); lastFrame = frame
return valueUnity C#
// One agent as the scheduler sees it: its own tree, and when it is next due.
public class ScheduledAgent
{
public Node Root; // this agent's tree
public float Interval; // seconds between ticks, set by level of detail
public float NextDue; // when its next tick is due
}
// Ticks the agents that are due, most overdue first, until the frame's budget is spent.
// An agent it does not reach stays due, so it is first in line next frame.
public class TickScheduler
{
readonly System.Collections.Generic.List<ScheduledAgent> agents =
new System.Collections.Generic.List<ScheduledAgent>();
readonly System.Diagnostics.Stopwatch clock = new System.Diagnostics.Stopwatch();
public void Add(ScheduledAgent agent, float now)
{
// Stagger: spread first ticks over one interval, so agents added together tick apart.
agent.NextDue = now + agent.Interval * (agents.Count % 10) / 10f;
agents.Add(agent);
}
// Call once a frame, e.g. Run(Time.time, 1.0) from a MonoBehaviour's Update.
// Returns how many agents it ticked.
public int Run(float now, double budgetMilliseconds)
{
agents.Sort((a, b) => a.NextDue.CompareTo(b.NextDue)); // most overdue first
clock.Restart();
int ticked = 0;
foreach (var agent in agents)
{
if (agent.NextDue > now) break; // nobody else is due
if (clock.Elapsed.TotalMilliseconds >= budgetMilliseconds) break; // the rest wait
agent.Root.Tick();
agent.NextDue = now + agent.Interval;
ticked++;
}
return ticked;
}
// Level of detail: every frame near the player, five times a second within 50 m, else once a second.
public static float LodInterval(float distanceToPlayer) =>
distanceToPlayer < 15f ? 0f : distanceToPlayer < 50f ? 0.2f : 1f;
}
// Works a costly value out at most once a frame, however many agents ask for it.
public class OncePerFrame<T>
{
readonly System.Func<T> compute;
int frame = -1;
T value;
public OncePerFrame(System.Func<T> compute) { this.compute = compute; }
public T Get(int currentFrame)
{
if (currentFrame != frame)
{
value = compute();
frame = currentFrame;
}
return value;
}
}
// The town's alarm, shared by every villager's TownAlarm condition:
// var townAlarm = new OncePerFrame<bool>(() => AnyThreatInsideTheWalls());
// new ConditionNode(() => townAlarm.Get(UnityEngine.Time.frameCount));GDScript
# One agent as the scheduler sees it: its own tree, and when it is next due.
class ScheduledAgent:
var root: BTNode
var interval := 0.0 # seconds between ticks, set by level of detail
var next_due := 0.0 # when its next tick is due
func _init(r: BTNode, i: float):
root = r
interval = i
# Ticks the agents that are due, most overdue first, until the frame's budget is spent.
# An agent it does not reach stays due, so it is first in line next frame.
class TickScheduler:
var agents: Array[ScheduledAgent] = []
func add(agent: ScheduledAgent, now: float) -> void:
# Stagger: spread first ticks over one interval, so agents added together tick apart.
agent.next_due = now + agent.interval * (agents.size() % 10) / 10.0
agents.append(agent)
# Call once a frame from _process, e.g. run(Time.get_ticks_msec() / 1000.0, 1000).
# Returns how many agents it ticked.
func run(now: float, budget_usec: int) -> int:
agents.sort_custom(func(a: ScheduledAgent, b: ScheduledAgent): return a.next_due < b.next_due)
var start := Time.get_ticks_usec()
var ticked := 0
for agent in agents:
if agent.next_due > now:
break # nobody else is due
if Time.get_ticks_usec() - start >= budget_usec:
break # the rest wait for next frame
agent.root.tick()
agent.next_due = now + agent.interval
ticked += 1
return ticked
# Level of detail: every frame near the player, five times a second within 50 m, else once a second.
static func lod_interval(distance_to_player: float) -> float:
if distance_to_player < 15.0:
return 0.0
if distance_to_player < 50.0:
return 0.2
return 1.0
# Works a costly value out at most once a frame, however many agents ask for it.
class OncePerFrame:
var compute: Callable
var frame := -1
var value: Variant
func _init(c: Callable):
compute = c
func get_value(current_frame: int) -> Variant:
if current_frame != frame:
value = compute.call()
frame = current_frame
return value
# The town's alarm, shared by every villager's TownAlarm condition:
# var town_alarm := OncePerFrame.new(func(): return any_threat_inside_the_walls())
# Condition.new(func(): return town_alarm.get_value(Engine.get_process_frames()))Unreal C++
// One agent as the scheduler sees it: its own tree, and when it is next due.
struct FScheduledAgent
{
TSharedPtr<FNode> Root; // this agent's tree
float Interval = 0.f; // seconds between ticks, set by level of detail
float NextDue = 0.f; // when its next tick is due
};
// Ticks the agents that are due, most overdue first, until the frame's budget is spent.
// An agent it does not reach stays due, so it is first in line next frame.
class FTickScheduler
{
public:
TArray<FScheduledAgent> Agents;
void Add(FScheduledAgent Agent, float Now)
{
// Stagger: spread first ticks over one interval, so agents added together tick apart.
Agent.NextDue = Now + Agent.Interval * (Agents.Num() % 10) / 10.f;
Agents.Add(Agent);
}
// Call once a frame, e.g. Run(GetWorld()->GetTimeSeconds(), 0.001) from an actor's Tick.
// Returns how many agents it ticked.
int32 Run(float Now, double BudgetSeconds)
{
const double Start = FPlatformTime::Seconds();
TArray<bool> Ticked;
for (int32 I = 0; I < Agents.Num(); ++I) Ticked.Add(false);
int32 Count = 0;
while (FPlatformTime::Seconds() - Start < BudgetSeconds) // the rest wait for next frame
{
int32 Next = -1; // the most overdue agent not yet ticked this frame
for (int32 I = 0; I < Agents.Num(); ++I)
{
if (Ticked[I] || Agents[I].NextDue > Now) continue;
if (Next < 0 || Agents[I].NextDue < Agents[Next].NextDue) Next = I;
}
if (Next < 0) break; // nobody else is due
Ticked[Next] = true;
Agents[Next].Root->Tick();
Agents[Next].NextDue = Now + Agents[Next].Interval;
++Count;
}
return Count;
}
// Level of detail: every frame near the player, five times a second within 50 m, else once a second.
static float LodInterval(float DistanceToPlayer)
{
if (DistanceToPlayer < 1500.f) return 0.f; // Unreal units are centimetres
if (DistanceToPlayer < 5000.f) return 0.2f;
return 1.f;
}
};
// Works a costly value out at most once a frame, however many agents ask for it.
template <typename T>
class TOncePerFrame
{
public:
explicit TOncePerFrame(TFunction<T()> InCompute) : Compute(MoveTemp(InCompute)) {}
const T& Get(int64 CurrentFrame) // e.g. GFrameCounter
{
if (CurrentFrame != Frame)
{
Value = Compute();
Frame = CurrentFrame;
}
return Value;
}
private:
TFunction<T()> Compute;
int64 Frame = -1;
T Value{};
};
// The town's alarm, shared by every villager's TownAlarm condition:
// TOncePerFrame<bool> TownAlarm([this] { return AnyThreatInsideTheWalls(); });
// FCondition([&TownAlarm] { return TownAlarm.Get(GFrameCounter); });
A scheduler like this sits above the trees, so it works with any of the node types on these pages and with the code beetree generate writes. To use it with generated Unity code, give each villager’s ScheduledAgent a Root that ticks the villager’s generated tree, and call Run from one manager’s Update instead of ticking each villager from its own. Set each agent’s Interval from LodInterval once a frame, and write player_distance to its blackboard at the same time, so the tree’s Within check reads the number the scheduler already worked out.
What BeeTreeCraft shows today
- The simulator runs one tree for one agent, one tick at a time. It shows the cost of a tick as the leaves in the trace: count the
●lines, as above, to compare two orders of the same tree. It has no clock, no tick rate and no second agent. - A custom node names what it reads with
blackboard_reads, so a shared value such astown_alarmis visible in the tree file and in the generated code.beetree validatedoes not check those names yet. - The generated Unity and Godot code build one copy of the tree for each agent (
Buildin Unity, the tree definition node in Godot), and each agent ticks its own copy; there is no shared definition, scheduler or level of detail in the generated code. The scheduler above works with it unchanged. Unreal’s behavior tree assets are shared by the engine, with per-agent node memory. - Explore runs several agents at once in the browser, each with its own tree.
Where it comes from
Alex Champandard and Philip Dunstan’s The Behavior Tree Starter Kit (Game AI Pro) builds a runtime twice: first with the state inside each node, then with the tree’s shared data apart from each agent’s small block of state, and ends with event-driven ticking. Damian Isla’s Handling Complexity in the Halo 2 AI (2005) keeps a large tree affordable: stimulus behaviors join the tree only when an event calls for them, and tags switch off whole branches a character never needs. Tommy Thompson’s Combat Evolved: The Encounter Design of Halo 3 (2018) drives whole squads from one task tree with shared squad knowledge. Epic’s Behavior Tree in Unreal Engine: Overview explains services and why Unreal’s trees are event-driven instead of ticked from the root every frame. More reading is on the Resources page.
Next, read Newer ideas: authoring and repair with a model to let a model draft and repair trees behind checks of your own, or open the Build hub, paste the townsfolk into the builder and use Step through to play a far villager and a near one, or read the tree format to declare the shared values a tree reads.