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.
On this page
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.

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/.
The first thirty seconds
Section titled “The first thirty seconds”-
Open
Assets/_Project/Scenes/HordeSurvival.unity. The folder also holdsHordeBenchmark.unity, which drives itself for measurement: ignore this one while you are playing. -
Select Bootstrap in the Hierarchy. Its Graph Enemy Brain Composer holds
HordeEnemy.bqbehaviorfor every enemy; on the same component, the Director Graph field holdsHordeDirector.bqbehaviorfor the run, and the Shared Difficulty field holds the authoredAssets/_Project/Variable/WaveDifficulty.asset, the one Core value the director’swave_difficultyfield shares with every destination that later reads it. -
Press Play and move. The HUD names the director’s current phase and shows the next surge countdown.
-
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.
-
Relax stops new batches for a while; enemies already on the field keep coming for you.
-
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.

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.

SHARED card reads 1, tagged shared WaveDifficulty, above its private rows.
1.75 typed into the Value field of WaveDifficulty’s own Inspector.
SHARED card after that Inspector edit: 1.75, with the recent-change tint.
2.5 typed into the SHARED card itself, again with the recent-change tint.
3: the HUD’s red difficulty label reads 3 during a swarm surge, with the wave warning chip at the top.
time 0:00, and difficulty is back at 1, the configured start.What this game teaches
Section titled “What this game teaches”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.

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.
Graph versus game code
Section titled “Graph versus game code”| 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.
Follow one decision
Section titled “Follow one decision”

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.

running, run 2, and last child result running while this cycle is active.
has_target true. The rail is showing the entity blackboard, not the Repeat’s selected status.
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.

Take one attack decision, from game data to a visible hit.
-
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. -
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. -
When all prechecks pass, Reset Attack Tally clears
attacks_landedto zero once for a fresh eligible Attack Sequence entry. Attack Flurry wraps Until Ready in Count3; the inner retry checks distance and contact radius before testing cooldown for each grant. A Running child has not spent a counted attempt. -
Grant Attack writes
AttackIntent.Ready; Attack Tally incrementsattacks_landedonly after that grant. Attack Flurry finishes after three completed grants, withattacks_landedat3. The attack preserves chase movement intent toward the survivor. -
ContactDamageSystemconsumes 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 reaches3through three new grants, without carrying the first burst’s tally.

attacks_landed at 3, and selected status success.
3; the new first grant brings attacks_landed to 1 while the second run is active.
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.
Brutes choose a tactic
Section titled “Brutes choose a tactic”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 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.
-
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, stance0, facing the keeper.
Figure 17. One staged Brute at full health with no allies nearby, closing straight in on the keeper and facing it squarely. -
Flank combines
brute_flank_rangeandbrute_ally_densityby 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 at90, turned side-on and banked into the curve.
Figure 18. One staged Brute surrounded by ten allies, running a curving line around the keeper, turned side-on. -
Retreat scores
brute_healththrough a curve that reads1at empty health and0at 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 at180, back turned and leaning away.
Figure 19. One staged Brute at 7.2 of 90 health, pulling straight back from the keeper, back turned.

is_brutegates 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.
BruteTacticTargetSystemturns the committedBruteTacticChoice.TacticIdinto 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 sameMovementIntentMode.Chasethe rest of the graph already uses.BruteStancePresentationSystemturns 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).
Change something and watch
Section titled “Change something and watch”Use this in your own game
Section titled “Use this in your own game”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
| Symptom | Check | Fix |
|---|---|---|
| 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. |
What next
Section titled “What next”- Racing Line: the last chapter, where a graph steers rich existing vehicle code.
- Performance: the recorded frame time and allocation figures from
HordeBenchmark, with the machine and the date attached. Running the benchmark yourself is optional. - Director with weighted choices: the phase and weight pattern on its own.
- Attack with cooldown: the enemy branch as a reusable shape.
- Keep going: read the three Repeat policies and their Live progress on one enemy.
- Entity debugging: everything the Live view offers on an entity, and what it withholds.
- Choose another sample.
Credits and reuse
Section titled “Credits and reuse”The keeper and the horde are by Kenney, who also supplies the ground and gives away thousands of game assets for free:
- Graveyard Kit: the keeper and the zombies, plus the graveyard dressing around the arena.
- Retro Textures Fantasy: the ground texture.
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.