Summary
A behaviour tree (BT) is a hierarchical decision structure for reactive AI. Instead of storing one current state and hard-coding transitions between states, a BT repeatedly ticks from the root downward, asking which branch should run now. This makes BTs especially good for NPCs that must constantly reprioritise between competing behaviours such as fleeing, attacking, investigating, or patrolling. (Yannakakis and Togelius, Artificial Intelligence and Games, see source-ai-and-games; Millington, Artificial Intelligence for Games, see source-artificial-intelligence-for-games)
Key ideas
- Selector: returns success on the first child that succeeds; use for priorities.
- Sequence: returns failure on the first child that fails; use for multi-step requirements.
- Decorator: wraps a child and modifies how it runs or returns.
- Leaf node: an action or condition.
- Ticking: the tree is re-evaluated repeatedly, which keeps the AI reactive.
- Blackboard/context: shared memory the nodes can read and write.
Implementation
public enum NodeState { Success, Failure, Running }
public abstract class BTNode
{
public abstract NodeState Tick();
}
public sealed class SelectorNode : BTNode
{
private readonly List<BTNode> children;
public SelectorNode(List<BTNode> children) => this.children = children;
public override NodeState Tick()
{
foreach (BTNode child in children)
{
NodeState result = child.Tick();
if (result != NodeState.Failure)
return result;
}
return NodeState.Failure;
}
}In Unity, keep BT nodes as plain C# classes rather than MonoBehaviours. The agent owns the tree and calls root.Tick() from Update().
Trade-offs
- Better than ai-state-machine-pattern when an NPC has many overlapping priorities.
- Heavier to debug than a tiny FSM if the tree grows without tooling or naming discipline.
- Still reactive: by itself, a BT does not plan long action sequences the way goal-oriented-action-planning does.
Examples
- Dragon Age: Inquisition combines tree-like execution structures with utility-style evaluation (Hanlon and Watts, Game AI Pro 360, see source-game-ai-pro-360-character-behavior).
- Modern production AI often uses BTs as the readable designer-facing layer even when lower systems handle steering, navigation, or utility scoring.
Related
game-ai-agent-design · overview-cre341-agent-ai-route · behaviour-trees-vs-goap · ai-state-machine-pattern · goal-oriented-action-planning · utility-ai · source-ai-and-games · source-artificial-intelligence-for-games