Skip to content
Bit Quirky Behavior Trees and
State Machines

Search documentation

All topics and APIs

Close returns focus to Search.

What are you looking for?

Try a common topic or enter a complete API identifier.

Browse the reference instead

Esc closes · Tab reaches results · Enter opens the focused link

v0.11.0
Menu

Horde Survival

Every enemy in a two thousand strong horde decides through one graph file, a second graph instance picks the pressure phase, and ECS keeps spawning, movement, and damage.

Thousands of zombies want your keeper, and every one of them decides through the same graph file. One more instance of a different graph, running on its own entity, decides how hard the game is leaning on you this second.

Enemies cross the real gameplay field toward the keeper while more arrive at its edges.
Enemies cross the real gameplay field toward the keeper while more arrive at its edges.

Play it in one minute

Under a minute

Scene
Assets/_Project/Scenes/HordeSurvival.unity
Select
Bootstrap in the Hierarchy
Controls
Keyboard: move with WASD or the arrow keys, restart with R once the run has ended. Gamepad: move with the left stick; restart is keyboard only. Attacks are automatic.
Goal
Stay alive while the director cycles its pressure phases, and read the phase on the HUD before the horde reaches you.

Paths here belong to the standalone project and start at Assets/_Project. A packaged sample import puts the same folders under Assets/BitQuirky/BehaviorTreesAndStateMachines/Samples/.

  1. Open Assets/_Project/Scenes/HordeSurvival.unity. The folder also holds HordeBenchmark.unity, which drives itself for measurement: ignore this one while you are playing.

  2. Select Bootstrap in the Hierarchy. Its Graph Enemy Brain Composer holds HordeEnemy.bqbehavior for every enemy; on the same component, the Director Graph field holds HordeDirector.bqbehavior for the run, and the Shared Difficulty field holds the authored Assets/_Project/Variable/WaveDifficulty.asset, the one Core value the director’s wave_difficulty field shares with every destination that later reads it.

  3. Press Play and move. The HUD names the director’s current phase and shows the next surge countdown.

  4. When build up ends, the director chooses a surge profile: swarm, rush, or brute. Read the profile and enemy count on the HUD while the enemies keep moving toward the survivor.

  5. Relax stops new batches for a while; enemies already on the field keep coming for you.

  6. When your health reaches zero the run ends and the panel shows your survival time. Press R to run again. Nothing resets while the run is alive.

The keeper alone in the graveyard arena with the first few zombies closing in.
Figure 1. Early in a run, before the director has leaned on you. The gameplay camera keeps the survivor centered, so the crowd on screen is only ever a slice of the population.

Select the running director in the Entities Hierarchy while the Behavior Tree Editor follows it: the wave_difficulty field appears in its own SHARED group ahead of the director’s private fields. It names WaveDifficulty and shows its current value editable in place. Editing WaveDifficulty in its own Inspector, or editing the row in the graph, reaches the same asset either way and refreshes both by the next tick. WaveDifficulty ships with a configured starting value of one. Horde’s new-run action (the R key, or the player.restart/director.seed commands, docs/commands.md) raises Core’s own shared reset exactly once, ahead of the ECS reset that clears the board, so a run you edited during play returns WaveDifficulty to that configured start rather than the value you last set, the director’s next wave resumes its original interval, and the wave warning’s pulse speed and tone pitch return to their starting behavior, and its volume does too, through the same Core change notification that drove the raise. A shared value with no configured starting value is left exactly where a designer last set it; a new run never invents one.

Raising WaveDifficulty above its authored baseline of one also shortens the director’s next spawn gap: the scene’s single GameLogicRunner (Hierarchy root, next to Bootstrap) drives one game-owned WavePacing domain asset that reads WaveDifficulty directly and divides each authored profile interval by the current difficulty, so every future wave arrives sooner without a restart or a graph rebake. At the authored baseline the result is numerically identical to the original per-profile interval; the rule and its generated GameLogicList/DataObjectIndex caches live under Assets/_Project/GameLogic/. Core is mounted only in Horde for this; the behavior product and graph package stay Core-independent. The director’s Resume Build Up reads paced_phase_elapsed, which the graph adapter fills every tick from WavePacing. It is Relax time as WavePacing paces it: unchanged at baseline, faster at higher difficulty. The transition compares it with the unchanged relax_minimum_duration dial, so Relax ends and the next Surge arrives sooner. Surge and Build Up lengths never change, and WavePacing is the one rule for both spawn gaps and the Relax gate. A difficulty at or below zero counts as baseline everywhere.

WaveDifficulty also drives what you see and hear on the HUD, entirely through reusable Core bindings authored on the HUD and WaveWarning GameObjects, never a Horde-specific synchronization script. A red difficulty label under wave on the HUD shows the current value directly (difficulty 1 at the authored baseline). The wave warning chip at the top of the screen beats on a loop: its dot pops, its ring pings outward, and the chip flashes red, at a playback speed bound to WaveDifficulty through the Animator’s WarningSpeed parameter. Its AudioSource plays one warning pip per beat with pitch and volume bound to the same asset; pitch shares the pulse’s curve, so the pip stays on the beat. At the authored baseline of one a beat lasts 0.8 seconds and the pip plays at pitch 1.0/volume 0.3; at a raised difficulty of three a beat lasts 0.4 seconds (twice as fast) and the pip plays an octave higher and louder, at pitch 2.0/volume 0.5. Raise WaveDifficulty in its Inspector during a run and watch the HUD number, the pulse speed, and the pip together, alongside the shortening spawn gaps above.

The Behavior Tree Editor’s Blackboard following the running director: the SHARED group holds wave_difficulty at 1 with a shared WaveDifficulty chip, above the director’s private HOST AUTHORITATIVE rows.
Figure 2. Baseline: the director’s SHARED card reads 1, tagged shared WaveDifficulty, above its private rows.
The WaveDifficulty asset’s Inspector during Play, its Value field reading 1.75.
Figure 3. 1.75 typed into the Value field of WaveDifficulty’s own Inspector.
The same SHARED wave_difficulty card now reads 1.75 and is tinted as just changed.
Figure 4. The director’s SHARED card after that Inspector edit: 1.75, with the recent-change tint.
The SHARED wave_difficulty card reads 2.5 and is tinted as just changed.
Figure 5. 2.5 typed into the SHARED card itself, again with the recent-change tint.
The Horde HUD seven seconds into a run, its red difficulty label reading 3, with the wave warning chip at the top.
Figure 6. Raised to 3: the HUD’s red difficulty label reads 3 during a swarm surge, with the wave warning chip at the top.
The Horde HUD at time 0 of a new run, its red difficulty label reading 1.
Figure 7. The next run: time 0:00, and difficulty is back at 1, the configured start.

Entity agents at scale: every living enemy runs the same baked HordeEnemy.bqbehavior and advances inside a Burst job over ECS buffers, one schedule per update for the whole horde. Entity runtime covers registration and ticking; Burst and jobs covers what compiles.

Entity member bindings: the brain reads ContactAttack.CooldownRemaining off the enemy’s own component, checks DeadFade.enabled, reads SurvivorTarget through a singleton, and writes movement and attack intent. See entity bindings.

Repeat on one enemy: Attack Flurry counts three completed real grants, Pursuit retries until the enemy reaches contact range, and the Forever pill above Enemy Decisions restarts the entire Selector after each completed cycle. Keep going explains the same three policies without changing the Platformer example.

A static member with arguments: the node named Distance Squared invokes math.distancesq with the enemy’s LocalTransform.Position and the survivor’s position, and surfaces the answer as distance_sq for the condition below it. See arguments and results.

A weighted director: HordeDirector.bqbehavior is a state machine of three phases whose Surge state hosts a Random Selector where the swarm branch carries a weight of 5 against 3 for rush and 2 for brute. See roll the dice and a tree inside a state.

The Horde director in Static mode with its three phase states and all four transitions, each carrying its predicate rows.
Figure 8. The whole director. Build Up leaves on an All group of elapsed time and population, Surge leaves on an Any group, and Relax has two ways back.

Graph values as the designer’s dials: seven declared values hold every phase boundary, so pacing is an edit in a window. See variables and types.

Beside those seven, wave_difficulty is a host input field: unlike a declared variable, the director’s own input binder fills it every tick from the injected WaveDifficulty asset, so the director, the HUD, the warning pulse, and the warning tone all track one live number with no synchronization code between them. See variables and types for how a shared value earns that identity, live editing and attach and inspect for editing and watching it run, and presentation destinations for the three Core bindings that read it.

Entity Live: pause, pick one enemy out of the crowd, and read the branch it took. See entity debugging.

Select a Repeat pill in Live to see that decorator’s own retained status, run progress, and last child result. Clear selection to read the evaluated branch cards. A failed Pursuit Attempt can sit beneath a running Pursuit: the wrapper is waiting to try again.

What stays in C#: the graphs never create an enemy, never move one, and never take a point of health off anybody. Horde’s ECS systems own all of that, which is why the decision layer can be deleted without taking the game with it.

A scored branch: inside the same graph, a Brute-profiled enemy also runs Choose Tactic, a Utility Selector gated behind an is_brute condition. It scores its three tactics from four live values bound to ordinary ECS facts, TacticFacts (health, nearness, flank range) and NearbyAllyDensity, refreshed before every tick, then hands the running tactic to a rival branch the instant that rival scores higher. See weigh it up for the node itself and brutes choose a tactic below for this graph’s own branch.

The graphs decide Horde’s ECS owns
HordeEnemy.bqbehavior, one instance per living enemy, registered by GraphEnemyBrainComposer on Bootstrap WaveSpawnSystem creates enemies on the spawn ring and holds the population under the 2,400 ceiling
HordeDirector.bqbehavior, one instance on the single director entity, registered by GraphDirectorComposer DirectorSpawnCadenceSystem turns the published decision into batch requests at the profile’s interval
Attack readiness: Grant Attack sets AttackIntent.Ready after contact and cooldown checks; Reset Attack Tally clears attacks_landed at the start of each eligible fresh flurry, and Attack Tally adds one for each grant ContactDamageSystem turns that same-frame grant into real contact damage and starts the per-enemy cooldown; ContactAttackCooldownSystem ages it
Movement intent: the brain writes MovementIntent.Mode with a target position FlowFieldMovementService is the only thing in the project that moves an enemy
Pursuit repeats the chase decision until contact range, Acquire Target locks a published survivor, and the Forever pill restarts Enemy Decisions after a complete result ECS publishes the target, moves the enemy through the flow field, and owns its lifecycle
Phase choice: the director’s actions fire build_up, swarm, rush, brute or relax The adapter’s command handler maps each action to one HordeDirectorDecision, and HudPresenter shows the result
Brute tactic choice: the profile-gated Choose Tactic Utility Selector scores its three tactics from live values bound to TacticFacts and NearbyAllyDensity, then commits the result to BruteTacticChoice.TacticId and a BruteStance cue TacticFactSystem writes TacticFacts and AllyDensitySystem writes NearbyAllyDensity every frame; BruteTacticTargetSystem turns the committed tactic into the actual MovementIntent.TargetPosition; BruteStancePresentationSystem turns the stance into rotation

Everything with Graph in its name lives in Assets/_Project/Runtime/GraphAdapter/. That folder is the only place in the project that references the product packages; the gameplay assembly references neither, and a package isolation test fails the build if either dependency leaks in. The two composers are the pieces worth copying: one registers a graph against an EntityQuery of agents, the other registers a graph against a single entity with an input binder and a command handler.

These are not the game. HardCodedEnemyBrainComposer under Runtime/Ports/ is the C# reference brain the graph brain was measured against, and neither shipped scene composes it. HordeBenchmark.unity with its own subscene drives the survivor along a fixed path, disables her death, and records frame times. Editing either one changes nothing you can play.

A selected Pursuit Repeat reports its Until success progress in read-only Live while the enemy closes on the keeper.
A selected Pursuit Repeat reports its Until success progress in read-only Live while the enemy closes on the keeper.
Selected Pursuit Until Success is Running on run 511 while its failed Pursuit Attempt and Pursuit Progress sit above successful target and distance cards.
Figure 9. One paused enemy in ordinary pursuit: selected Pursuit shows Until Success, status running, run 511, and last child result failed. Its Pursuit Attempt and Pursuit Progress cards report Failure; Read Current Survivor, Validate Target, Has Target Pursuit, and Distance Squared Chase report Success.

The selected Pursuit rail shows its own status and run progress during ordinary movement, while the cards show the last evaluated child results. The unsuccessful target-lock handoff is different: Acquire Target succeeds immediately on an already published survivor, then Awaiting Target fails the complete Enemy Decisions Selector. Forever remains Running and starts the next decision at Is Dead. After a complete attack or pursuit Success it starts there too; destroying the enemy ends its own loop.

Selected Forever Repeat in Horde Live is Running on its next decision cycle.
Figure 10. Selected Forever reads status running, run 2, and last child result running while this cycle is active.
Unselected Horde Live view shows Enemy Decisions failing after its target-lock handoff.
Figure 11. An unselected card reports the complete Selector’s Failure after the lock, with has_target true. The rail is showing the entity blackboard, not the Repeat’s selected status.
Selected Forever reading shows a second run following a completed enemy decision.
Figure 12. After that complete failed cycle, selected repeat forever stays Running on run 2; last child result reads failed for the finished Selector.

HordeEnemy.bqbehavior is a statechart whose Enemy state hosts a tree. repeat forever wraps Enemy Decisions. Its Selector checks Death, then Attack Sequence, then Chase Sequence, then Wander. A fresh attack attempt measures distance and checks contact radius. It also waits for the cooldown to clear before resetting the flurry tally. If a precheck fails, the Selector can choose pursuit or wander.

Paused Horde attack prechecks beside their selected read-only detail, followed by a separately selected idle Attack Flurry on Count 3.
Figure 13. The paused prechecks show Distance Squared Precheck succeeding and In Contact Radius Precheck failing, so Cooldown Ready Precheck has not started. A separate paused enemy’s selected Attack Flurry is idle and shows its authored Count of three.

Take one attack decision, from game data to a visible hit.

  1. Distance Squared Precheck reads the enemy position and the survivor position, computes distance_sq_precheck, and In Contact Radius Precheck tests the contact radius against it.

  2. Cooldown Ready Precheck reads ContactAttack.CooldownRemaining. If the enemy is still waiting, Attack Sequence fails before starting a new flurry, so Chase Sequence or Wander gets a turn.

  3. When all prechecks pass, Reset Attack Tally clears attacks_landed to zero once for a fresh eligible Attack Sequence entry. Attack Flurry wraps Until Ready in Count 3; the inner retry checks distance and contact radius before testing cooldown for each grant. A Running child has not spent a counted attempt.

  4. Grant Attack writes AttackIntent.Ready; Attack Tally increments attacks_landed only after that grant. Attack Flurry finishes after three completed grants, with attacks_landed at 3. The attack preserves chase movement intent toward the survivor.

  5. ContactDamageSystem consumes each grant in the same frame, takes health off the survivor, and starts that enemy’s existing cooldown. The graph grants permission; the system does the hitting. After the completed burst, the cooldown precheck yields to chase or wander. The next eligible fresh burst runs Reset Attack Tally again and reaches 3 through three new grants, without carrying the first burst’s tally.

The selected Attack Flurry Count finished at completed 3 of 3 with attacks_landed at 3.
Figure 14. First finished flurry: three counted grants, attacks_landed at 3, and selected status success.
On the next fresh flurry, Attack Flurry is Running on run 2 of 3 with attacks_landed at 1.
Figure 15. The same observed enemy later enters another eligible flurry. Reset Attack Tally has cleared its prior 3; the new first grant brings attacks_landed to 1 while the second run is active.
The Horde gameplay camera shows zombies closing around the keeper.
Figure 16. Camera-only gameplay at the contact arena. The frame does not expose an individual enemy’s attack count or the HUD; read those facts in selected Live.

To watch one entity, pause Unity mid-run, select an enemy row under the live World, and read the hosted tree in Live. The toolbar marks it Read-only. Evaluated cards carry status pills; select the Attack Flurry Count decorator to read its own status, run 2 of 3 while a second attempt is active, or completed 3 of 3 once the third finishes. A completed Until Success says completed without a made-up run total. The rendered zombie has no GameObject to click.

Among a Brute surge’s enemies, the same HordeEnemy.bqbehavior graph runs one extra branch: an is_brute condition gates Choose Tactic, a Utility Selector scoring three tactics every tick: rush, flank, and retreat. It runs whichever currently reads highest. Every other profile skips the branch entirely and keeps its existing Chase Sequence and Wander subtree. The director’s own rush surge profile, which sends many ordinary enemies in fast, is unrelated to this brute’s own rush tactic.

A staged Brute steps through rush, flank, and retreat as its health, distance, and ally facts change in turn.
A staged Brute steps through rush, flank, and retreat as its health, distance, and ally facts change in turn.

A staged Brute steps through its three tactics by hand, one phase at a time, so each is easy to tell apart. In an ordinary wave the same facts shift continuously: health, distance, and ally crowding, and the brute’s tactic tracks them the same way.

To watch the switching in a real Brute surge, hold the keeper still while the first brutes walk in, then walk toward a group and away again. Build-up zombies fall to a single keeper strike, so a keeper standing still is still alive when the brutes arrive. A brute your strikes wounded turns and retreats once you pull far enough away that its lost health outscores its nearness, and brutes chasing you in a bunch break off to flank.

  1. Rush scores directly from brute_proximity, how close the brute already is to the keeper. With no allies nearby to compete, rush wins: the brute closes in a straight line, stance 0, facing the keeper.

    One staged Brute at full health with no allies nearby, closing straight in on the keeper and facing it squarely.
    Figure 17. One staged Brute at full health with no allies nearby, closing straight in on the keeper and facing it squarely.
  2. Flank combines brute_flank_range and brute_ally_density by Minimum, so it only wins once the brute is both close enough and surrounded. The brute runs a curving line around the keeper, its stance at 90, turned side-on and banked into the curve.

    One staged Brute surrounded by ten allies, running a curving line around the keeper, turned side-on.
    Figure 18. One staged Brute surrounded by ten allies, running a curving line around the keeper, turned side-on.
  3. Retreat scores brute_health through a curve that reads 1 at empty health and 0 at full, so it climbs as health falls and eventually passes the other two. The brute pulls straight back out along its approach line, its stance at 180, back turned and leaning away.

    One staged Brute at 7.2 of 90 health, pulling straight back from the keeper, back turned.
    Figure 19. One staged Brute at 7.2 of 90 health, pulling straight back from the keeper, back turned.
Three staged Brutes at once, one rushing, one flanking, one retreating, each turned and leaning to match its tactic.
Figure 20. All three tactics at once. None of the three brutes changes size or color; the cue is pose alone: turn, lean, and bank.
  • is_brute gates the whole branch: every other profile never reaches Choose Tactic and keeps running its existing Chase Sequence or Wander subtree, unchanged.
  • Each tactic scores independently: rush from proximity, flank from flank range and ally density, retreat from health. Reshaping one tactic’s curve never moves the other two.
  • All three branches are authored to Interrupt: Choose Tactic re-picks the instant a rival strictly outscores the running tactic, so a brute never finishes a rush it should have abandoned two frames ago.
  • BruteTacticTargetSystem turns the committed BruteTacticChoice.TacticId into the actual chase point: the keeper’s position for rush, a point tangential to the keeper for flank, a point extrapolated outward through the brute for retreat, all through the same MovementIntentMode.Chase the rest of the graph already uses.
  • BruteStancePresentationSystem turns the brute toward its committed stance, with a forward lean and a sideways bank riding on top of that turn; it writes rotation only, after movement has placed the brute that frame, so every brute keeps its spawned size and the cue stays pose alone.

See weigh it up for the Utility Selector itself and the node reference for every field on its card.

Watch one Brute decide live: attach to it in Play Mode and its current Rush, Flank, and Retreat scores, plus its chosen tactic, appear in the debugger’s Utility scores rail, with a structured trace entry recorded on every tactic change; see entity debugging. Sampling the whole horde at once instead of one Brute, enemy.tactics reports each tactic’s live running count and score range across every Brute (docs/commands.md).

Copy the intent shape first. Two components, one for movement intent and one for attack permission, are the entire contract between the graph and the systems that already move and damage things in your game. A graph that writes only those two is one you can delete without breaking the simulation.

Copy the presentation bindings too. NumericLabelBinding, NumericAnimatorBinding, and NumericAudioSourceBinding are Core components, not Horde code: point their Source at a Core FloatVariable asset in your own project, then set each component’s own destination fields for its new host: NumericLabelBinding needs Document and Label Name, NumericAnimatorBinding needs Target and Parameter Name, and NumericAudioSourceBinding needs Target. With those set, the same text and animation-parameter tracking follows, and so does audio-property tracking, with no new C#. Presentation destinations covers the three.

Rebind the conditions. Member conditions in HordeEnemy.bqbehavior read Horde component types; point them at yours through the Member picker and keep the decision shape. Targets covers the target modes the entity host offers, including this brain’s singleton and static bindings.

New C# is needed for three jobs: an input binder that writes your facts into the blackboard ahead of the tick, a command handler for each named action the graph fires, and a composition step that registers the graph against the query of agents that should run it. Horde’s two composers are the worked example, and the director’s one adds the validation that its seven phase values stay inside the game’s own ceiling.

Two practical limits before you scale up. Entity member bindings need Burst AOT in a player, with no managed fallback, and entity Live is an observer with no per-entity pause. Adding a graph branch that writes an intent nobody consumes gives you a graph that succeeds and a game that does not change.

When it goes wrong

SymptomCheckFix
Clicking an enemy opens nothing.Confirm what you clicked in the Scene view.Search t:Enemy and select the entity row instead.
No live world is listed.Confirm Play mode is running.Press Play and let a wave spawn first.
Editor reads "Selected entity no longer exists."Assume that enemy died, as most do.Select a living row. A reused index is a new version.
Every enemy holds still.Read whether the survivor target is enabled.Restore the target. Hold is right with nothing to chase.
Attack succeeds, health never drops.Follow the attack permission to its reader.Inspect the contact damage system. The graph only grants.
Chase is set, the enemy stays put.Read that entity movement data.Inspect the flow field service, which owns movement.
Phase changes, no batch spawns.Read the profile interval and the ceiling.Inspect the spawn cadence system. Relax blocks batches.
Composition rejects a new surge limit.Compare it with the build up maximum.Keep it above that value and at or below 2,400.
A saved graph edit looks ignored.Confirm the run restarted after the save.Start a fresh run. Live entities keep their graph.
A spawned Brute never flanks or retreats.Confirm the enemy is actually profiled Brute, and that allies or low health are really present nearby.Only EnemyProfile.Value Brute reaches Choose Tactic; flank and retreat also need ally density or lost health to outscore rush.

The keeper and the horde are by Kenney, who also supplies the ground and gives away thousands of game assets for free:

We took ours from Kenney Game Assets All-in-1, the paid bundle of everything Kenney has released; the links above go to the same packs on kenney.nl, where each one is a free download.

Both are CC0, which asks nothing of you and allows commercial use; we always credit Kenney when we use their assets, and support them by buying the packs. We hope you will too! The imported subsets sit under Assets/ThirdParty/Kenney/ beside their License.txt files. Keep each license file with any art you copy out, so the next person knows where it came from. The ECS gameplay code, the Bit Quirky packages, and the Kenney art are separate works with separate terms.

Full-size image