Table of Contents

Quick Answer

A behavior tree is a hierarchical decision-making structure used in game AI to control NPC and enemy behavior. Here’s what you need to know:

  • Trees execute from root to leaves, evaluating nodes until finding an action to perform
  • Composite nodes (Sequences and Selectors) control execution flow
  • Leaf nodes perform actual actions or check conditions
  • Blackboards store shared data between nodes
  • Most major engines (Unreal, Unity, Godot) support behavior trees natively or via plugins

What is a Behavior Tree?

A behavior tree (BT) is a hierarchical model for organizing AI decision-making in games. Originally developed for robotics, behavior trees became the industry standard for game AI after being popularized by Halo 2’s enemy AI system.

Think of a behavior tree like a flowchart that constantly asks: “What should I do right now?” The tree evaluates from the root node downward, checking conditions and executing actions until it finds something the AI can do.

Unlike finite state machines where you explicitly define every transition between states, behavior trees let you compose complex behaviors from simple, reusable building blocks. This makes them easier to debug, extend, and maintain as your AI requirements grow.

Why Use Behavior Trees Over State Machines?

State machines work great for simple AI, but they hit a wall as complexity increases. Here’s why behavior trees often win for game AI:

Scalability: Adding new behaviors to a state machine requires defining transitions to and from every existing state. In a behavior tree, you just add new branches — existing logic stays untouched.

Readability: A well-structured behavior tree reads almost like pseudocode: “First, check if the player is visible. If so, attack. Otherwise, patrol.” State machine diagrams become spaghetti as states multiply.

Reusability: Behavior tree nodes are self-contained. That “MoveTo” node you wrote for the guard AI? Drop it into the merchant AI with zero modifications.

Debugging: When your AI acts weird, you can trace exactly which branch executed and why. Each node returns Success, Failure, or Running — no hidden state transitions to hunt down.

That said, state machines aren’t obsolete. Many games use both: state machines for high-level modes (Combat, Patrol, Flee) and behavior trees for the detailed decision-making within each mode.

Core Concepts: Nodes, Sequences, and Selectors

Every behavior tree is built from three types of nodes: composite nodes, decorator nodes, and leaf nodes.

Leaf Nodes: Actions and Conditions

Action nodes are where work happens. “Move to position,” “Play attack animation,” “Fire weapon” — these are all actions. An action returns:

  • Success when the action completes successfully
  • Failure when the action can’t be performed
  • Running when the action is still in progress

Condition nodes check the world state. “Is player in range?” “Am I low on health?” “Is the door locked?” Conditions typically return Success or Failure immediately — they don’t have a Running state.

Composite Nodes: Sequences and Selectors

Sequence nodes execute children left-to-right until one fails. Think of them as AND logic: “Do A AND B AND C.” If any child fails, the sequence fails immediately. If all children succeed, the sequence succeeds.

Example sequence for attacking:

  1. Check if player is visible (condition)
  2. Move within attack range (action)
  3. Play attack animation (action)
  4. Deal damage (action)

If the player breaks line of sight during step 2, the sequence fails and the tree can try something else.

Selector nodes (also called Fallback nodes) execute children until one succeeds. Think OR logic: “Try A OR B OR C.” This is perfect for fallback behaviors.

Example selector for combat:

  1. Try melee attack (if in range)
  2. Try ranged attack (if has ammo)
  3. Try to close distance
  4. Flee

The AI attempts each option in priority order until something works.

Decorator Nodes

Decorators wrap a single child and modify its behavior. Common decorators include:

  • Inverter: Flips Success to Failure and vice versa
  • Repeater: Runs the child multiple times
  • Succeeder: Always returns Success, regardless of child result
  • Until Fail: Keeps running child until it fails
  • Cooldown: Prevents child from running again for X seconds

Building Your First Behavior Tree

Let’s build a practical example: a guard NPC that patrols, investigates sounds, and attacks enemies.

Step 1: Define the Behaviors

Start by listing what your AI needs to do in plain English:

  • Attack any visible enemy
  • Investigate suspicious sounds
  • Patrol between waypoints when idle

Step 2: Structure as a Selector

The root is a selector because we want fallback priority. Combat takes precedence over investigation, which takes precedence over patrol:

Selector (Root)
├── Sequence: Combat
├── Sequence: Investigate  
└── Sequence: Patrol

Step 3: Flesh Out Each Branch

Combat Sequence:

Sequence: Combat
├── Condition: Is Enemy Visible?
├── Action: Set Target
├── Selector: Choose Attack
│   ├── Sequence: Melee Attack
│   │   ├── Condition: In Melee Range?
│   │   └── Action: Melee Attack
│   └── Sequence: Ranged Attack
│       ├── Condition: Has Ammo?
│       └── Action: Ranged Attack
└── Action: Face Target

Investigate Sequence:

Sequence: Investigate
├── Condition: Heard Sound?
├── Action: Set Investigation Point
├── Action: Move To Point
└── Action: Look Around

Patrol Sequence:

Sequence: Patrol
├── Action: Get Next Waypoint
├── Action: Move To Waypoint
└── Action: Wait (2 seconds)

Step 4: Add a Blackboard

The blackboard is shared memory that nodes read from and write to. For our guard, we might store:

  • CurrentTarget — The enemy we’re fighting
  • InvestigationPoint — Where we heard a sound
  • CurrentWaypoint — Our patrol destination
  • LastKnownEnemyPosition — For searching

Nodes query and update the blackboard rather than passing data directly. This keeps nodes decoupled and reusable.

Advanced Patterns and Best Practices

Parallel Nodes

Parallel nodes run multiple children simultaneously. Useful for behaviors like “move to cover while suppressing the enemy.” You configure how many children must succeed for the parallel to succeed.

Subtrees

As trees grow, extract common patterns into subtrees. That “MoveTo with obstacle avoidance” logic? Make it a subtree and reference it from multiple places. Changes propagate automatically.

Memory and Persistence

Some implementations support “memory” — resuming a running node where it left off instead of re-evaluating from the root every tick. This prevents the AI from constantly restarting long-running actions.

Event-Driven vs. Polling

Basic behavior trees poll every frame: evaluate the whole tree, execute whatever succeeds. More sophisticated implementations use events: only re-evaluate relevant branches when the world state changes. This saves CPU and enables reactive AI.

Debugging Tips

  • Visualize execution: Color-code nodes by their last return value. Green for Success, red for Failure, yellow for Running.
  • Log transitions: When branches change, log why. “Switched from Patrol to Combat because EnemyVisible became true.”
  • Slow it down: Add a debug mode that steps through one node per keypress.

Implementation in Popular Engines

Unreal Engine

Unreal has built-in behavior tree support with a visual editor. Key features:

  • Native Blackboard system
  • Service nodes that run in the background (like constantly updating perception)
  • Decorator nodes for conditions
  • Environment Query System (EQS) integration for spatial reasoning

Create a new Behavior Tree asset, set up an AI Controller, and wire it to your character. Unreal’s documentation covers the specifics well.

Unity

Unity doesn’t include behavior trees natively, but you have options:

  • Unity’s Behavior package (com.unity.behavior) — Official solution released in 2024
  • NodeCanvas — Popular paid asset with visual editor
  • Behavior Designer — Another solid paid option
  • Roll your own — The architecture is straightforward if you prefer control

Godot

Godot’s approach is more DIY, but several community solutions exist:

  • Beehave — Popular open-source addon
  • Godot Behavior Tree — Another community option
  • GDScript makes implementing your own tree surprisingly pleasant

Pro Tips

  • Start simple: Get a basic selector working before adding complexity. A two-branch tree that works beats a ten-branch tree that doesn’t.
  • Name nodes clearly: “CheckPlayerVisible” beats “Condition1.” Your future self will thank you.
  • Test branches in isolation: Before wiring up the full tree, verify each sequence works on its own.
  • Use subtrees for repeated patterns: If you’re copy-pasting node structures, extract them.
  • Profile before optimizing: Behavior trees rarely bottleneck performance. Measure first.
  • Consider hybrid approaches: State machines for high-level states, behavior trees for decision-making within states.
  • Document your blackboard: What each variable means, who writes it, who reads it. Saves hours of debugging.

Frequently Asked Questions

How often should I tick my behavior tree?

Most games tick every frame, but you can reduce frequency for performance. 10-20 times per second is often enough for non-player characters. Use events for urgent reactions (like taking damage) rather than relying on polling.

Can I use behavior trees for player characters?

Technically yes, but it’s unusual. Behavior trees model autonomous decision-making. Players make their own decisions — you’d use them more for AI companions that follow the player.

What’s the difference between a behavior tree and a decision tree?

Decision trees make a single decision by traversing conditions to a leaf. Behavior trees orchestrate ongoing behavior, handling sequences, parallel actions, and the Success/Failure/Running state model. Behavior trees are better for game AI; decision trees suit one-shot classification.

How do I handle interrupts (like taking damage)?

Several approaches: (1) Check conditions every tick that can abort the current branch, (2) Use decorator nodes that abort on condition changes, (3) Implement event-driven trees that re-evaluate on specific triggers. Unreal’s “Observer Aborts” feature handles this elegantly.

Should I write my own behavior tree system?

If you’re learning, absolutely — it’s a great exercise. For production, consider existing solutions first. Battle-tested implementations handle edge cases you haven’t thought of yet.

Summary

Behavior trees offer a powerful, scalable approach to game AI that outgrows simple state machines. By composing reusable nodes into hierarchical structures, you can build complex NPC behaviors that are easy to debug and extend.

Start with the basics: sequences for ordered actions, selectors for fallbacks, and a blackboard for shared state. As your AI needs grow, layer in decorators, parallel nodes, and subtrees. Most importantly, test incrementally — a working simple tree teaches you more than a broken complex one.

Whether you use Unreal’s built-in system, a Unity plugin, or roll your own, the underlying concepts remain the same. Master them once, and you’ll have a tool that serves you across every project.