Hybrids: utility, state machines and planners
A behavior tree does not have to make every decision alone. Put a state machine above it, a utility score inside it, or a planner in one of its leaves, and let each method do the part it is best at.
A behavior tree is good at one kind of decision: a short list of options in a fixed order of priority, checked again on every tick. Flee if hurt, else fight if an enemy is near, else patrol. Some decisions do not fit that shape, and forcing them in makes a tree long and fragile. Most shipped game AI is a hybrid: a behavior tree working next to another way of deciding, each doing the part it is best at.
This page covers the three partners you meet most often: a utility score inside a tree, a state machine around it, and a planner inside one of its leaves.
Three kinds of decision a tree finds hard
Weighing options by degree. A selector asks yes-or-no questions in a fixed order. “Shoot if the enemy is in range” is easy. “Shoot, take cover or charge, whichever is best right now, given distance, health and ammo” is not: the order itself should change from tick to tick. That is what utility scoring is for.
Staying in a mode. A tree re-decides from the root on every tick. That is what makes it react quickly, but some behavior should be sticky: once a guard has decided to go and restock, a single quiet tick should not send it back to patrol halfway there. A state machine is built for modes that last.
Finding a sequence of steps. A tree runs the steps its author wrote down. When the right steps depend on the world (the arrows are in the store, the store is locked, the key is with the cook), writing every case as a branch does not scale. A planner works the steps out when they are needed.
Utility inside a tree
A utility score is a number, usually from 0 to 1, that says how good an option is right now. Each score is built from considerations: small measures such as “how close is the enemy” or “how much health is left”, each turned into a number from 0 to 1 by a response curve and then multiplied together. Because they are multiplied, one consideration at 0 rules an option out, whatever the others say. A designer’s weight then scales the result, so one option can be preferred over another without changing any curve.
A utility selector is a selector whose children are tried in order of score instead of the order they are written in. It scores every child, runs the best one, and falls back to the next best when the best one fails, the way a plain selector falls back to its next child. The scores are worked out again on every tick, so the order follows the situation.
In a tree file, the utility selector is the node type utility_selector. The tree around it keeps its usual job: it decides whether to fight, and the utility selector decides how. That split keeps the scores small: they only compare fighting moves, not fighting against eating.
A state machine around trees
A state machine is a set of states (modes such as guard, fight and restock) and transitions between them (rules such as “from guard to fight when an enemy is spotted”). It is in exactly one state at a time, and it stays there until a transition fires. Before behavior trees, most game AI was written this way, and it is still the clearest way to describe modes that last.
The two mix in either direction. A state can run a tree while it is active, which is how the AI of Final Fantasy XV combines them: a state machine for the large modes, and a tree for what to do inside each one. Or a tree can hold a state machine: the current state is a blackboard variable, each top branch is guarded by a condition on it, and each transition is an action that writes it. The tree on this page does the second, so the whole thing is one file the simulator can run.
A planner in a leaf
A planner is given a goal (“stocked with arrows”) and a list of actions, each with what must be true before it (its preconditions) and what it makes true (its effects). It searches for a list of actions that leads from the world as it is to a world where the goal holds. That list is the plan. GOAP (goal-oriented action planning, made famous by F.E.A.R.) searches over actions in this way. HTN planners (hierarchical task networks) instead break a large task into smaller ones by rules an author writes, which keeps the search small.
In a hybrid, the tree decides when to plan and what to do with the plan. One leaf asks the planner and writes the plan to the blackboard; it fails when no plan exists, so a fallback branch can take over. The next leaf runs the plan one step at a time and returns Running until the last step is done. When the world changes under the plan, the tree notices on its next tick and plans again.
A tree you can run
The mercenary guards a camp. Its top selector is a state machine with three states, kept in the blackboard variable mode: guard, fight and restock. Each state is one branch: a condition that checks mode, and the behavior of that state. In a fight, a utility selector picks the move. To restock, a planner works out the steps.
# file: mercenary.beetree.yaml
version: "1.0"
metadata:
name: mercenary
description: "A camp mercenary: a state machine of three modes on top, a utility choice of tactic in a fight, and a planner that works out how to restock"
tags: [hybrids, utility, state-machine, planner]
blackboard:
- {name: mode, type: string, default: "guard", description: "The current state: guard, fight or restock. Written by the transitions; read by in_mode"}
- {name: plan, type: string, description: "The steps the planner chose, written by make_plan and read by follow_plan"}
custom_nodes:
- name: InMode
type: condition
description: "Succeeds when mode equals the parameter: the guard on one state of the state machine"
parameters:
- {name: mode, type: string}
blackboard_reads: [mode]
- name: SetMode
type: action
description: "Writes mode: a transition to another state"
parameters:
- {name: mode, type: string}
blackboard_writes: [mode]
- name: EnemyNear
type: condition
description: "Succeeds when an enemy is within sight"
- name: Tactic
type: action
description: "One fighting move; the utility selector scores it with its considerations, scaled by weight"
parameters:
- {name: weight, type: float, default: 1.0}
- name: LowOnSupplies
type: condition
description: "Succeeds when arrows or food run low"
- name: MakePlan
type: action
description: "Asks the planner for steps that reach the goal, and writes them to plan; fails when no plan exists"
parameters:
- {name: goal, type: string}
blackboard_writes: [plan]
- name: FollowPlan
type: action
description: "Runs the next step of plan; Running until the last step is done"
blackboard_reads: [plan]
- name: Patrol
type: action
description: "Walks the camp's edge"
tree:
type: selector
name: mercenary_root
children:
- type: sequence
name: fight_state
children:
- {type: condition, name: in_fight, node: InMode, parameters: {mode: fight}}
- type: selector
name: fight_or_leave
children:
- type: sequence
name: keep_fighting
children:
- {type: condition, name: enemy_near, node: EnemyNear}
- type: utility_selector
name: pick_tactic
children:
- {type: action, name: shoot, node: Tactic, parameters: {weight: 1.0}}
- {type: action, name: take_cover, node: Tactic, parameters: {weight: 0.8}}
- {type: action, name: charge, node: Tactic, parameters: {weight: 0.5}}
- {type: action, name: fight_to_guard, node: SetMode, parameters: {mode: guard}}
- type: sequence
name: restock_state
children:
- {type: condition, name: in_restock, node: InMode, parameters: {mode: restock}}
- type: selector
name: restock_or_give_up
children:
- type: sequence
name: plan_and_go
children:
- {type: action, name: make_plan, node: MakePlan, parameters: {goal: stocked}}
- {type: action, name: follow_plan, node: FollowPlan}
- {type: action, name: restock_to_guard, node: SetMode, parameters: {mode: guard}}
- {type: action, name: give_up_restock, node: SetMode, parameters: {mode: guard}}
- type: sequence
name: guard_state
children:
- {type: condition, name: in_guard, node: InMode, parameters: {mode: guard}}
- type: selector
name: guard_or_leave
children:
- type: sequence
name: spot_enemy
children:
- {type: condition, name: enemy_spotted, node: EnemyNear}
- {type: action, name: guard_to_fight, node: SetMode, parameters: {mode: fight}}
- type: sequence
name: notice_supplies
children:
- {type: condition, name: supplies_low, node: LowOnSupplies}
- {type: action, name: guard_to_restock, node: SetMode, parameters: {mode: restock}}
- {type: action, name: patrol, node: Patrol}
Read the state machine off the tree. Each state is a sequence whose first child is the guard in_<state>. Each transition is a SetMode action named <from>_to_<to>, placed where its rule holds: guard_to_fight runs only after enemy_spotted succeeded. A state with nothing left to do (no enemy near, or no plan) transitions back to guard. Because mode stays set between ticks, the mercenary stays in restock until the plan is done or fails, however quiet the camp is.
Check it and run the quiet case, in the guard state with nothing to do:
beetree validate mercenary.beetree.yaml
beetree simulate mercenary.beetree.yaml --override in_fight=FAILURE --override in_restock=FAILURE --override enemy_spotted=FAILURE --override supplies_low=FAILURE
Simulation: mercenary_root → SUCCESS
──────────────────────────────────────────────────
▶ ? mercenary_root
▶ → fight_state
● ¿ in_fight → FAILURE
◀ → fight_state → FAILURE
▶ → restock_state
● ¿ in_restock → FAILURE
◀ → restock_state → FAILURE
▶ → guard_state
● ¿ in_guard → SUCCESS
▶ ? guard_or_leave
▶ → spot_enemy
● ¿ enemy_spotted → FAILURE
◀ → spot_enemy → FAILURE
▶ → notice_supplies
● ¿ supplies_low → FAILURE
◀ → notice_supplies → FAILURE
● ! patrol → SUCCESS
◀ ? guard_or_leave → SUCCESS
◀ → guard_state → SUCCESS
◀ ? mercenary_root → SUCCESS
Now the fight state, where the best move fails. Here shoot has no clear line, so the utility selector falls back to the next move, and take_cover is still under way:
beetree simulate mercenary.beetree.yaml --override shoot=FAILURE --override take_cover=RUNNING
Simulation: mercenary_root → RUNNING
──────────────────────────────────────────────────
▶ ? mercenary_root
▶ → fight_state
● ¿ in_fight → SUCCESS
▶ ? fight_or_leave
▶ → keep_fighting
● ¿ enemy_near → SUCCESS
▶ ⚖ pick_tactic
● ! shoot → FAILURE
● ! take_cover → RUNNING
◀ ⚖ pick_tactic → RUNNING
◀ → keep_fighting → RUNNING
◀ ? fight_or_leave → RUNNING
◀ → fight_state → RUNNING
◀ ? mercenary_root → RUNNING
The ⚖ marks the utility selector. The simulator has no scores, so it tries the moves in the order they are written, which here is also the order of their weights. In a game, the scores decide the order, and they change as the fight does.
Last, the restock state: the planner found a plan, and the mercenary is following it:
beetree simulate mercenary.beetree.yaml --override in_fight=FAILURE --override follow_plan=RUNNING
Simulation: mercenary_root → RUNNING
──────────────────────────────────────────────────
▶ ? mercenary_root
▶ → fight_state
● ¿ in_fight → FAILURE
◀ → fight_state → FAILURE
▶ → restock_state
● ¿ in_restock → SUCCESS
▶ ? restock_or_give_up
▶ → plan_and_go
● ! make_plan → SUCCESS
● ! follow_plan → RUNNING
◀ → plan_and_go → RUNNING
◀ ? restock_or_give_up → RUNNING
◀ → restock_state → RUNNING
◀ ? mercenary_root → RUNNING
Add --override make_plan=FAILURE and the selector falls back to give_up_restock, which sends the mercenary back to guard.
Engine code
The samples build on the Node and Status of Building blocks. Each has two parts.
UtilitySelector takes its children and one score function per child. On each tick it scores every child once, then tries them from best to worst until one does not fail. A child that scores 0 is never tried, and when all score 0 the node fails. Utility.Score multiplies a weight by its considerations, and Utility.Linear is the simplest response curve: 0 below a low value, 1 above a high one, a straight line between.
Planner.Plan is a small GOAP planner. Each PlanAction names the facts it needs and the facts it gives. The planner searches breadth-first from the facts that are true now, so the first plan it finds is one of the shortest. It returns the names of the steps, or nothing when no plan of at most maxSteps reaches the goal. A MakePlan leaf calls it and writes the result to the blackboard; a FollowPlan leaf runs the steps.
Agnostic
UtilitySelector(children, scores) // one score function per child
tick():
s = [score() for score in scores] // scored again on every tick
for i in children, from highest s to lowest:
if s[i] <= 0: return FAILURE // nothing left worth doing
status = children[i].tick()
if status != FAILURE: return status
return FAILURE
score(weight, considerations) = weight * product(considerations) // each from 0 to 1
linear(value, low, high) = 0 below low, 1 above high, a straight line between
plan(now, goal, actions, maxSteps): // GOAP, breadth-first
frontier = [(now, [])]
while frontier:
(facts, steps) = frontier.popFront()
if goal in facts: return steps
if len(steps) == maxSteps: continue
for a in actions where a.needs are all in facts and a.gives are not:
frontier.add((facts + a.gives, steps + [a.name]))
return noneUnity C#
// Tries its children from the highest score to the lowest, scored again on every tick,
// and falls back to the next best when one fails, as a Fallback falls back to its next child.
public class UtilitySelector : Node
{
readonly Node[] children;
readonly System.Func<float>[] scores; // one per child, from 0 to 1
public UtilitySelector(Node[] children, System.Func<float>[] scores)
{
this.children = children;
this.scores = scores;
}
public override Status Tick()
{
var score = new float[children.Length];
for (int i = 0; i < children.Length; i++) score[i] = scores[i]();
var tried = new bool[children.Length];
for (int round = 0; round < children.Length; round++)
{
int best = -1;
for (int i = 0; i < children.Length; i++)
{
if (!tried[i] && (best < 0 || score[i] > score[best])) best = i;
}
if (score[best] <= 0f) return Status.Failure; // nothing left worth doing
tried[best] = true;
var status = children[best].Tick();
if (status != Status.Failure) return status;
}
return Status.Failure;
}
}
public static class Utility
{
// A weight times its considerations; any consideration at 0 rules the option out.
public static float Score(float weight, params float[] considerations)
{
float score = weight;
foreach (var c in considerations) score *= c;
return score;
}
// A response curve: 0 at or below low, 1 at or above high, a straight line between.
public static float Linear(float value, float low, float high) =>
value <= low ? 0f : value >= high ? 1f : (value - low) / (high - low);
}
// One thing the planner may do: the facts it needs first, and the facts it makes true.
public class PlanAction
{
public readonly string Name;
public readonly string[] Needs;
public readonly string[] Gives;
public PlanAction(string name, string[] needs, string[] gives)
{
Name = name;
Needs = needs;
Gives = gives;
}
}
public static class Planner
{
class Partial
{
public System.Collections.Generic.HashSet<string> Facts;
public System.Collections.Generic.List<string> Steps;
}
// Breadth-first from the facts true now to a state where goal holds: one of the
// shortest lists of step names, or null when none of at most maxSteps reaches it.
public static System.Collections.Generic.List<string> Plan(string[] now, string goal,
PlanAction[] actions, int maxSteps = 6)
{
var frontier = new System.Collections.Generic.Queue<Partial>();
frontier.Enqueue(new Partial
{
Facts = new System.Collections.Generic.HashSet<string>(now),
Steps = new System.Collections.Generic.List<string>(),
});
while (frontier.Count > 0)
{
var at = frontier.Dequeue();
if (at.Facts.Contains(goal)) return at.Steps;
if (at.Steps.Count == maxSteps) continue;
foreach (var a in actions)
{
if (!at.Facts.IsSupersetOf(a.Needs) || at.Facts.IsSupersetOf(a.Gives)) continue;
var next = new Partial
{
Facts = new System.Collections.Generic.HashSet<string>(at.Facts),
Steps = new System.Collections.Generic.List<string>(at.Steps) { a.Name },
};
next.Facts.UnionWith(a.Gives);
frontier.Enqueue(next);
}
}
return null;
}
// The mercenary's restock: the arrows are in the store, and the store is locked.
public static System.Collections.Generic.List<string> Restock() => Plan(
new[] { "at_camp" }, "stocked", new[]
{
new PlanAction("ask_cook_for_key", new[] { "at_camp" }, new[] { "has_key" }),
new PlanAction("walk_to_store", new[] { "at_camp" }, new[] { "at_store" }),
new PlanAction("unlock_store", new[] { "at_store", "has_key" }, new[] { "store_open" }),
new PlanAction("take_arrows", new[] { "store_open" }, new[] { "stocked" }),
});
// -> ask_cook_for_key, walk_to_store, unlock_store, take_arrows
}GDScript
# Tries its children from the highest score to the lowest, scored again on every tick,
# and falls back to the next best when one fails, as a Fallback falls back to its next child.
class UtilitySelector extends BTNode:
var children: Array[BTNode]
var scores: Array[Callable] # one per child, returning 0.0 to 1.0
func _init(c: Array[BTNode], s: Array[Callable]):
children = c
scores = s
func tick() -> Status:
var score: Array[float] = []
var tried: Array[bool] = []
for s in scores:
score.append(s.call())
tried.append(false)
for _round in children.size():
var best := -1
for i in children.size():
if not tried[i] and (best < 0 or score[i] > score[best]):
best = i
if score[best] <= 0.0:
return Status.FAILURE # nothing left worth doing
tried[best] = true
var status := children[best].tick()
if status != Status.FAILURE:
return status
return Status.FAILURE
# A weight times its considerations; any consideration at 0 rules the option out.
static func utility_score(weight: float, considerations: Array[float]) -> float:
var score := weight
for c in considerations:
score *= c
return score
# A response curve: 0 at or below low, 1 at or above high, a straight line between.
static func linear(value: float, low: float, high: float) -> float:
return clampf((value - low) / (high - low), 0.0, 1.0)
# Breadth-first from the facts true now to a state where goal holds: one of the
# shortest lists of step names, or an empty array when none reaches it.
# Each action is {"name": String, "needs": Array, "gives": Array}.
static func plan(now: Array, goal: String, actions: Array[Dictionary], max_steps := 6) -> Array[String]:
var start := {}
for fact in now:
start[fact] = true
var frontier: Array = [[start, [] as Array[String]]]
var head := 0
while head < frontier.size():
var facts: Dictionary = frontier[head][0]
var steps: Array[String] = frontier[head][1]
head += 1
if facts.has(goal):
return steps
if steps.size() == max_steps:
continue
for a in actions:
if not facts.has_all(a["needs"]) or facts.has_all(a["gives"]):
continue
var next := facts.duplicate()
for fact in a["gives"]:
next[fact] = true
var path := steps.duplicate()
path.append(a["name"])
frontier.append([next, path])
return []
# The mercenary's restock: the arrows are in the store, and the store is locked.
static func restock() -> Array[String]:
return plan(["at_camp"], "stocked", [
{"name": "ask_cook_for_key", "needs": ["at_camp"], "gives": ["has_key"]},
{"name": "walk_to_store", "needs": ["at_camp"], "gives": ["at_store"]},
{"name": "unlock_store", "needs": ["at_store", "has_key"], "gives": ["store_open"]},
{"name": "take_arrows", "needs": ["store_open"], "gives": ["stocked"]},
])
# -> ask_cook_for_key, walk_to_store, unlock_store, take_arrowsUnreal C++
// Tries its children from the highest score to the lowest, scored again on every tick,
// and falls back to the next best when one fails, as a Fallback falls back to its next child.
class FUtilitySelector : public FNode
{
public:
TArray<TSharedPtr<FNode>> Children;
TArray<TFunction<float()>> Scores; // one per child, from 0 to 1
EStatus Tick() override
{
TArray<float> Score;
TArray<bool> Tried;
for (const TFunction<float()>& S : Scores)
{
Score.Add(S());
Tried.Add(false);
}
for (int32 Round = 0; Round < Children.Num(); ++Round)
{
int32 Best = -1;
for (int32 I = 0; I < Children.Num(); ++I)
{
if (!Tried[I] && (Best < 0 || Score[I] > Score[Best])) Best = I;
}
if (Score[Best] <= 0.f) return EStatus::Failure; // nothing left worth doing
Tried[Best] = true;
const EStatus Status = Children[Best]->Tick();
if (Status != EStatus::Failure) return Status;
}
return EStatus::Failure;
}
};
// A weight times its considerations; any consideration at 0 rules the option out.
inline float UtilityScore(float Weight, const TArray<float>& Considerations)
{
float Score = Weight;
for (float C : Considerations) Score *= C;
return Score;
}
// A response curve: 0 at or below Low, 1 at or above High, a straight line between.
inline float Linear(float Value, float Low, float High)
{
if (Value <= Low) return 0.f;
if (Value >= High) return 1.f;
return (Value - Low) / (High - Low);
}
// One thing the planner may do: the facts it needs first, and the facts it makes true.
struct FPlanAction
{
FString Name;
TArray<FString> Needs;
TArray<FString> Gives;
};
class FPlanner
{
public:
// Breadth-first from the facts true now to a state where Goal holds. Fills OutSteps
// with one of the shortest lists of step names; false when none of at most MaxSteps reaches it.
static bool Plan(const TArray<FString>& Now, const FString& Goal, const TArray<FPlanAction>& Actions,
TArray<FString>& OutSteps, int32 MaxSteps = 6)
{
TArray<FPartial> Frontier;
Frontier.Add(FPartial{Now, TArray<FString>()});
for (int32 Head = 0; Head < Frontier.Num(); ++Head)
{
const FPartial At = Frontier[Head];
if (Has(At.Facts, Goal))
{
OutSteps = At.Steps;
return true;
}
if (At.Steps.Num() == MaxSteps) continue;
for (const FPlanAction& A : Actions)
{
if (!HasAll(At.Facts, A.Needs) || HasAll(At.Facts, A.Gives)) continue;
FPartial Next = At;
for (const FString& Fact : A.Gives) Next.Facts.Add(Fact);
Next.Steps.Add(A.Name);
Frontier.Add(Next);
}
}
return false;
}
private:
struct FPartial
{
TArray<FString> Facts;
TArray<FString> Steps;
};
static bool Has(const TArray<FString>& Facts, const FString& Fact)
{
for (const FString& F : Facts)
{
if (F == Fact) return true;
}
return false;
}
static bool HasAll(const TArray<FString>& Facts, const TArray<FString>& Wanted)
{
for (const FString& W : Wanted)
{
if (!Has(Facts, W)) return false;
}
return true;
}
};To use the utility selector for the mercenary’s pick_tactic, give each move a score built from its considerations and its weight from the tree file. In Unity, for example, shoot could score Utility.Score(1.0f, Utility.Linear(ammo, 0, 5), lineOfSight ? 1f : 0f) and take_cover Utility.Score(0.8f, 1f - Utility.Linear(health, 20, 80)): with full health and a clear line, shooting wins; when health drops, cover wins, with no change to the tree.
The planner is deliberately small. A real GOAP planner gives each action a cost and searches with A* so the cheapest plan wins, not just the shortest, and it plans again when a step fails. An HTN planner replaces the search with rules that break a task into smaller tasks.
What BeeTreeCraft shows today
utility_selectoris a node type in the tree format.beetree rendermarks it[UTL], and the trace marks it⚖.- Neither simulator scores it.
beetree simulateand the builder try its children in the order they are written, so put them in the order you expect to be most common, and use--overrideto play out a best move that fails. - The generated Unity code has a
BTUtilitySelectorwith aScoremethod to override: it scores each child on every tick and tries them from best to worst. The generated Godot and Unreal code try the children in the order written; add scoring as in the samples above. - A custom node’s parameters carry a utility weight from the file into the code (the generated
TacticActiongetsWeight = 0.8f), andbeetree validatechecks the weight is a number. - There is no state machine node and no planner node. A state machine is written as on this page, with the state in a blackboard variable, and a planner lives behind a custom action.
Where it comes from
Dave Mark and Kevin Dill’s Building Utility Decisions into Your Existing Behavior Tree (Game AI Pro) adds utility scores to the selectors of a tree, as on this page. Behavior Selection Algorithms: An Overview (Game AI Pro) sets state machines, behavior trees, utility and planners side by side and says what each is good at. Simulating Behavior Trees: A Behavior Tree / Planner Hybrid Approach (Game AI Pro) lets a planner look ahead through a tree. Are Behavior Trees a Thing of the Past? weighs trees against the methods that came after them. More reading is on the Resources page.
Next, read Scale: many agents on one budget to keep a town of such trees affordable, or open the Build hub, paste the mercenary into the builder and use Step through to answer in_fight, in_restock and in_guard as the state would, then read the tree format to declare the blackboard variable that holds the state and the parameters that carry each weight.