๐ Welcome to AI Behavior Architect
AI Behavior Architect is a visual scripting tool and runtime framework designed from the ground up for Unity's Data-Oriented Technology Stack (DOTS) and the Entity Component System (ECS).
๐ก The DOTS Challenge
While there are many Behavior Tree solutions available for Unity, most are built around object-orientedMonoBehaviourworkflows. Attempting to force those object-oriented trees into an ECS environment often results in heavy memory allocations (Garbage Collection), thread-safety issues, and lost performance.
AI Behavior Architect solves this by bridging the gap between designer-friendly visual scripting and hardcore developer performance: designers author trees visually, and the framework automatically compiles them into Burst-compiled, allocation-free DOTS systems.
๐ฏ Who is this for?
- ๐จ For Designers: A clean, intuitive node-based editor right inside Unity. Design AI logic, manage sub-trees, configure blackboards, and watch visual debugging in real-timeโall without touching code.
- ๐ป For Programmers: A robust backend that takes that visual graph and uses a custom two-stage code generator (an editor-side file writer plus a Roslyn incremental source generator) to automatically write highly optimized, Burst-compiled
ISystemandIJobChunkC# scripts. You get the rapid iteration of visual scripting with the extreme runtime performance of pure DOTS code.
โจ Core Features at a Glance
- 100% DOTS Native: The entire tree evaluator and every generated action executes inside Burst-compiled jobs.
- Zero-GC Allocations: No runtime garbage collection. All per-agent state lives in unmanaged
DynamicBuffer<T>components; the whole compiled tree lives in a singleBlobAsset. - Auto-Code Generation: Press Compile and the framework generates the DOTS backend systems for your trees automatically โ including one shared system per unique node configuration.
- Advanced Spatial Queries: Built-in spatial-hashing Find node locates entities (First / Nearest / Random) without writing math.
- Parallel Execution: Per-agent trees evaluate in parallel across all agent entities via
ScheduleParallel. - Visual Runtime Debugging: Node borders light up live on the graph while Play Mode runs, with zero overhead in builds.
- Extensible via C#: Any
partial structtagged[BtCustom]becomes a node โ ports, inspector fields, queries and jobs are generated from the method signature.
๐ฆ Package Facts
| Property | Value |
|---|---|
| Package name | sniveler-code.dev.ai-behavior-architect |
| Display name | AI Behavior Architect |
| Current version | 1.1.x |
| Minimum Unity | 2022.3 (0f1) |
| Required dependencies | com.unity.entities 1.4.5, com.unity.entities.graphics 1.4.18, com.unity.burst 1.8.27, com.unity.mathematics 1.3.2, com.unity.collections 2.6.5 |
| Optional dependencies | URP / HDRP 14.0.9 (required by the Demo Workers sample only) |
| Render pipeline | Core framework is 100% pipeline-agnostic (Built-in, URP, HDRP) |
๐ How This Documentation is Organized
- Section 1โ2: What the package is, how it works under the hood, installation, setup and your first agent.
- Section 3: The editor: layout, sub-trees, and live debugging.
- Section 4: The blackboard โ the two-tier data system that connects nodes.
- Section 5: Complete reference of every built-in node with exact runtime semantics.
- Section 6: Writing custom nodes: the execution model, the full attribute API, component access and command buffers.
- Section 7: Runtime internals: the frame-by-frame pipeline, the blob memory layout, the full ECS component reference, and known pitfalls.
- Section 8: The Demo Workers stress-test sample and the test suite.
๐ง Core Concepts & Architecture
To get the most out of AI Behavior Architect โ especially when writing custom nodes or diagnosing runtime behavior โ it helps to understand the four stages a visual graph passes through on its way to executing DOTS code:
1. Editor compile โ 2. Roslyn code generation โ 3. Sub-scene bake โ 4. Per-frame runtime
| # | Stage | Where it runs | Reads | Produces |
|---|---|---|---|---|
| 1 | Editor compile | Editor โ BtCodeGenerator, triggered by the Compile button (or auto on save) | every GraphAsset in the project | SystemsNote.g.cs (the [BaSystemNodes] registry) + SnivelerCode.AiBehavior.Generated.asmdef, written into your Generated Directory |
| 2 | Roslyn code generation | the C# compiler โ AiBehaviorAnalyzer (incremental IIncrementalGenerator) | the [BtCustom] structs, [BtCondition] components and the generated [BaSystemNodes] class in your compilation | one Burst ISystem + IJobChunk per unique node configuration (custom actions, Find, Condition, Transaction), plus the shared BtBakingSystem and BtDispatcherSystem |
| 3 | Sub-scene bake | sub-scene baking โ BtAgentAuthoring.Baker, once per agent GameObject | the compiled registry + the agent's assigned GraphAsset | a BlobAssetReference<BtBlob> (the tree flattened into one contiguous unmanaged block), the per-agent state buffers (BtNodeState, BtActionState, BtBlackboardEntry, BtParallelBranchState), and bake requests (per-action Tag components + prefab registry entries) |
| 4 | Per-frame runtime | every simulation frame | the blob + the agent's state buffers | behavior: BtRunnerSystem ticks the tree; custom actions run in their own generated Burst jobs and report back (see Runtime Internals) |
โ๏ธ 1. Automated Code Generation (Two Stages)
Behavior Trees are inherently polymorphic (a generic "node" can be an Action, a Sequence, or a Condition). ECS does not support polymorphism โ everything must be strictly typed data. AI Behavior Architect bypasses this with a two-stage code generator:
Stage 1 โ Editor file writer (BtCodeGenerator).
When you press Compile (or it auto-runs on save, depending on your settings), the editor scans every GraphAsset in the project, extracts the unique node configurations (each Find query, each Condition set, each Transaction set, each custom action type) and writes two files into your Generated Directory:
SystemsNote.g.csโ a single[BaSystemNodes]class holding aBaSystem[] Nodesarray that registers every unique node configuration with a 64-bit hash index.SnivelerCode.AiBehavior.Generated.asmdefโ an assembly definition referencing the runtime, the DOTS packages, and the assemblies that actually contain your custom action structs and your[BtCondition]components (detected via reflection).
This stage is incremental: the content is hashed, and files are only rewritten (and Unity only recompiles) when the registry content actually changed.
Stage 2 โ Roslyn incremental source generator (Source~).
While Unity compiles, AiBehaviorAnalyzer (IIncrementalGenerator) reacts to three attribute families anywhere in your compilation:
| Trigger attribute | Target | Generated output |
|---|---|---|
[BtCustom("Name")] | your partial struct | Bt{HASH:X}System : ISystemplus the rest of your partial struct turned into a [BurstCompile] IJobChunk. Lives in your namespace. |
[BtCondition] | component structs | partial class ComponentsExtension with Compare(this ref T, ref BtCondition) and Modify(this ref T, ref BtCondition) โ the field-level condition/transaction evaluators used by Find, Condition and Change-Entity systems. |
[BaSystemNodes] | the generated SystemNodes class | One system per registry entry: Bt{HASH:X}System for Find (spatial hash), Condition (lookup compare) and Transaction (queue-driven modify) nodes, plus the shared BtBakingSystem and BtDispatcherSystem. Lives in SnivelerCode.AiBehavior.Generated. |
The 64-bit hash of a node configuration is an FNV-1a of a canonical string:
- Custom actions: the fully-qualified type name (namespace + struct name). Your struct is therefore registered by type, and the graph's node hash matches it exactly.
- Find / Condition / Change-Entity nodes: the sorted, de-duplicated list of the involved component type names plus the node kind (Find additionally includes its Spatial Cell Size โ changing the cell size produces a new system; changing Max Distance or Find Mode does not, because those are read from the blob at runtime).
๐ก Configuration sharing is by design. Two Find nodes in different graphs that query the same components with the same cell size share one generated system. Only entities whose trees actually use a running instance of that node carry its (enabled) Tag, so shared systems cost nothing for agents that don't use them.
๐ฆ 2. Blob Assets (BlobAssetReference<BtBlob>)
At bake time, BtAgentAuthoring's baker runs BtCompiler.Compile(graph) which flattens your visual tree โ following Sub-Tree nodes recursively โ into a compact, offset-based structure:
- a flat
BlobArray<BtNode>(type + parent/child/sibling indices), - a parallel
BlobArray<BtNodeData>of per-node data pointers, - pooled
FloatData(static parameters),Conditions(field masks + ops + values),Parallels,Hashes(node/prefab/port hashes) andBbIndices(blackboard slot indices) arrays.
That structure is written into a single BlobAsset (BtBlob) and attached to the agent entity as a BlobAssetReference<BtBlob> component inside BtAgent.
๐ Why Blob Assets?
The whole tree โ nodes, parameters, condition tables โ lives in one contiguous block of unmanaged memory. Walking it is cache-friendly, it is read-only, and it can be safely dereferenced with raw pointers inside Burst-compiled multithreaded jobs. NoGameObjectwalks, no virtual calls, no allocations.
The execution model is an iterative state machine (not recursion): the agent entity carries its resume point (BtAgent.CurrentNodeIndex) and the runner re-enters the tree at that node every frame. Every node transition is a small switch over NodeType, and per-node timers/counters live in the agent's unmanaged buffers. See Blob Layout Reference and Runtime Internals for the full layout and state machine.
๐พ 3. Unmanaged State Buffers
A Behavior Tree must remember what it was doing last frame (timers, loop counters, which actions are running). BtAgentAuthoring allocates the following unmanaged DynamicBuffer<T> components directly on the agent entity during baking:
| Buffer | Element type | Purpose |
|---|---|---|
BtNodeState | 4-byte float union (Value / IntValue / UIntValue) | Blackboard variable values, Wait/Delay timers, Cooldown timestamps, Retry/Repeater counters, random-visited bitmasks. Size = NodeStateCount from the compile step. |
BtActionState | {ActionHash, NodeIndex, Status} | One entry per currently running custom/Find/Condition node instance on this agent. The bridge between the runner and the generated action systems. |
BtBlackboardEntry | 16-byte unmanaged union (BtBlackboardValue) | The data-port blackboard: Entity ids, float3 positions and any other unmanaged โค16-byte value passed between nodes through horizontal ports. |
BtParallelBranchState | {CurrentNodeIndex, LastNodeIndex, Status} | One entry per Parallel child branch, so Parallel can resume each branch independently. |
Because all state is strictly unmanaged and packed onto the entity chunk, the runtime evaluator never touches the managed heap โ no List, no Dictionary, no string formatting (logging goes through BtLogger's FixedString-based builder, which is stripped in non-editor builds).
๐งฑ 4. The Frame Pipeline at a Glance
Per simulation frame (full details in Runtime Internals):
BtDebugInitSystem(editor only) โ ensures every agent has aBtDebugStatebuffer.BtRunnerSystemโ BurstIJobEntityscheduled in parallel over all agents. Ticks each tree as far as it can get (bounded by Max Iterations Per Frame), and requests custom actions instead of running them inline.BtDispatcherSystem(generated) โ drains the request queue and toggles the per-action Tag components (enabling/disabling action systems per agent) or enqueues transition requests for Change-Entity nodes.- Generated action systems (one per unique Find / Condition / custom action) โ Burst
IJobChunkjobs over the agents whose Tag is enabled; they call yourProcessmethod and write the resultingNodeStatusback intoBtActionState. BtSpawnSystemโ drains spawn requests from Create-Entity nodes and instantiates baked prefabs through anEndSimulationEntityCommandBuffer.- Next frame's Initialization group:
BtPrefabCacheSystem(keeps an O(1) prefab-hash โ entity map) andBtSpawnBlackboardSystem(copies newly spawned entities into the blackboard output ports).
The runner never calls action code inline: requests are queued, actions run in their own parallel jobs, and results are read back one or more frames later. This indirection is what makes the whole graph safely parallel โ and it is the single most important concept to internalize before writing custom nodes. See The Custom Action Execution Model.
๐ฅ Installation & Requirements
Before importing AI Behavior Architect, make sure your Unity project meets the requirements below. The package manifest declares the following (values from package.json of the current release):
๐ System Requirements
| Requirement | Minimum Version | Notes |
|---|---|---|
| Unity | 2022.3 (2022.3.0f1) | Any later 2022.3 LTS patch or 6000 series release works |
Entities (com.unity.entities) | 1.4.5 | Core ECS/DOTS package |
Entities Graphics (com.unity.entities.graphics) | 1.4.18 | Required by the package manifest; only needed if you render DOTS entities |
Burst Compiler (com.unity.burst) | 1.8.27 | Compiles the runner and all generated systems |
Mathematics (com.unity.mathematics) | 1.3.2 | float3, quaternion, Random, โฆ |
Collections (com.unity.collections) | 2.6.5 | NativeQueue, NativeParallelMultiHashMap, โฆ |
| URP / HDRP (optional) | 14.0.9 | Only required by the Demo Workers sample |
๐ก Render Pipeline Compatibility
The core AI framework is 100% render-pipeline agnostic. It relies purely on ECS and the Job System, so it works identically under the Built-in Render Pipeline, URP and HDRP โ whether or not your agents are rendered through Entities.Graphics at all (you can drive classicMonoBehaviour-adjacent systems from the same trees).
๐ฆ Installation
AI Behavior Architect is a private package โ it is not published to any public registry (there is no OpenUPM / scoped registry entry and no public git URL). You install it one of two ways:
Option A โ Package Manager: local package (shows up in My Assets)
- Place the
sniveler-code.dev.ai-behavior-architectpackage folder (the one containing the package'spackage.json) somewhere on disk โ outside your project is the common layout, inside works too. - In Unity: Window โ Package Manager (with the Project package view selected) โ click the
+button โ Add package from diskโฆ - Select the package folder.
- The package now appears under Packages โ My Assets (and in the Project Packages list); Unity resolves Entities, Entities.Graphics, Burst, Mathematics and Collections automatically from the manifest.
๐ก A disk-referenced package is a live folder: to upgrade, replace the folder's contents with the new package version (keeping the folder path) and press Refresh in the Package Manager โ nothing to re-import.
Option B โ Import a .unitypackage
- Obtain the current
AI Behavior Architect.unitypackagefrom the publisher. - In Unity: Assets โ Import Package โ Custom Packageโฆ and select the file.
- Unity imports the package into your project and resolves the DOTS dependencies for you.
Samples (both options):
- Option A: open Package Manager โ Packages โ My Assets โ AI Behavior Architect โ Samples โ Demo Workers โ Import to get the stress-test scene.
- Option B:
.unitypackagefiles don't carry theSamples~folder โ copy the sample'sScripts,PrefabsandScenefolders into your project manually (theGpuAnimationscripts inside are demo-only support code and can be skipped if you don't need the animated characters).
โ Post-Installation Checklist
- Wait for the first compile. The package ships with editor + runtime assemblies and the Roslyn source generator; Unity performs one full compile on first open.
- Open Project Settings (
Edit โ Project Settings โ AI Behavior Architect) and verify the Generated Directory โ see Project Setup. - (Optional) Demo Workers: the sample requires URP. After importing it, run AI Behavior Architect โ Demo Workers โ Setup URP Pipeline (see Demo Workers Sample).
- Smoke test: follow the Quick Start to create a graph, compile it and watch it light up in Play Mode.
โ ๏ธ Generated code and asmdef are created on the first Compile, not at import time. The generated assembly (
SnivelerCode.AiBehavior.Generated) must be able to reference the assemblies that contain your custom actions and your[BtCondition]components โ if you move code between assemblies, press Compile once more so the generated.asmdefpicks up the new references.
โ๏ธ Project Setup
Because AI Behavior Architect writes C# code for you, the first thing to configure is where that generated code goes โ and understanding what the generator produces.
1. Configuring the Generator
Open Edit โ Project Settings.
Select the AI Behavior Architect tab in the left-hand menu (the settings provider registers it under
Project/AI Behavior Architect).Generated Directory โ the folder where generated sources and the generated
.asmdefare written. Default:Assets/SnivelerCode/AiBehavior/Generated. Use the Browse button to pick any folder underAssets/.Auto Compile On Save โ when enabled (default), the generator re-runs automatically at key moments:
- when the Behavior Editor window is closed,
- when you switch the active tree in the toolbar,
- when you enter Play Mode (the graph is saved and recompiled first, so the bake always sees the latest data).
When disabled, code generation only happens when you explicitly click Compile in the editor.
โ ๏ธ Important: never hand-edit files inside the Generated Directory. They are overwritten the next time the content hash changes. Treat the folder like
bin/.
2. What "Compile" Actually Writes
The Compile button (bottom of the left panel) does two things:
- Persists the current graph asset to disk first โ the generated code and the next DOTS bake both read from the saved asset, so the on-disk data is always in sync.
- Scans every
GraphAssetin the project (not just the open one), collects all unique node configurations and writes:
SystemsNote.g.cs
A registry class consumed by the Roslyn source generator:
[assembly: AlwaysLinkAssembly]
namespace SnivelerCode.AiBehavior.Generated
{
[BaSystemNodes]
public class SystemNodes
{
public BaSystem[] Nodes = new BaSystem[]
{
new BaFind
{
CellSize = 10,
Index = 18101929384756482103, // FNV-1a of the node configuration
Components = new[] { "MyGame.PlayerTag" }
},
new BaCondition
{
Index = 2710883825131385922,
Components = new[] { "MyGame.HealthComponent" }
},
new BaTransaction
{
Index = 10645025438390241920,
Components = new[] { "Unity.Transforms.LocalTransform" }
},
new BaCustom
{
Index = 15436213217446092321,
Components = new[] { "MyGame.AI.MoveAction" }
}
};
}
}
Indexis the FNV-1a 64-bit hash of the node configuration (see Core Concepts for the exact strings hashed).Componentscarries the fully-qualified type names the node operates on.
SnivelerCode.AiBehavior.Generated.asmdef
An assembly definition that references:
- the base set:
Unity.Burst,Unity.Entities,Unity.Mathematics,Unity.Collections,Unity.Transforms,SnivelerCode.AiBehavior.Runtime, - plus every non-system assembly that contains a type referenced by your trees โ your custom action structs (
[BtCustom]) and your[BtCondition]components. These references are discovered by reflecting the assemblies in the editor.
๐ก Why this matters: if your custom actions live in a custom assembly (e.g.
MyGame.AI), that assembly is added to the generated asmdef automatically. If you later move an action into another assembly and don't re-Compile, the generated assembly won't see it and the Roslyn generator won't emit its system โ nodes using it will fail at bake time. Re-Compile whenever code assembly boundaries change.
3. Incremental Generation
The writer hashes the generated SystemsNote.g.cs content and skips the write entirely when nothing changed โ so pressing Compile on an unchanged project is a no-op, and Unity won't recompile. This keeps the workflow fast: edits to a graph that don't change node configurations (e.g. moving nodes around, changing a Wait duration) do not trigger a recompile at all; they only take effect after the next bake (next Play Mode entry), because the runtime data lives in the blob, not in code.
| Change you make | Code regenerated? | Re-bake needed? |
|---|---|---|
| Move/drag nodes, change graph view transform | No | Yes (Play Mode) |
| Change a node's parameter (Wait time, Find distance, blackboard value) | No | Yes (Play Mode) |
| Add/remove a component in Find/Condition/Change-Entity | Yes (new hash โ new system) | Yes |
| Change a Find node's Spatial Cell Size | Yes (cell size is part of the hash) | Yes |
| Change a Find node's Max Distance or Find Mode | No (runtime data from blob) | Yes |
Add a new [BtCustom] action type to your code | Not by the editor โ the Roslyn generator picks it up on the next compile of your assembly | Yes |
Change a [BtCustom] Process signature | Roslyn generator on next compile | Yes |
Add a new GraphAsset that reuses existing configs | No | Yes |
4. The BtSettings Asset
The settings UI persists to a BtSettings ScriptableObject. On first use the provider auto-creates it at Assets/Settings/BtSettings.asset. It only stores the two generator options above โ runtime behavior settings (iteration limits, warnings) are separate and live on your scene, see Runtime Internals.
๐ Quick Start: Your First AI Agent
Let's build your first DOTS-driven AI agent from scratch. We'll create a simple behavior that makes an entity wait in place โ then extend it into a real, reactive tree.
Step 1 โ Create the Behavior Graph
- In the Project window, right-click anywhere.
- Go to Create โ Entities โ Sniveler Code โ AI Graph and name it, e.g.
MyFirstAgent. - Open the editor: Window โ Sniveler Code โ AI Behavior Architect.
- Drag the
MyFirstAgentasset into the Active Tree slot in the top toolbar.
Step 2 โ Add Logic Nodes
- Right-click the empty grid (or press
Spacebar) to open the Node Search Window. - Search for Composite Sequence (under Composites) and click it to place a
Sequencenode. - Search for Action Wait (under Actions) and place a
Waitnode to its right. - Drag from the bottom (Output) flow port of the
Sequenceto the top (Input) flow port of theWait. - Select the
Waitnode โ in the left panel, set its value to, say,3(seconds).
๐ Rule of thumb: the node you connect out of is the parent, the node you connect into is the child. Trees always flow top โ bottom. A graph has exactly one root โ the node that no other node points at.
Step 3 โ Compile the Tree
- In the left panel, click Compile.
- Watch the Console: you should see
[BT Architect] Graph compiled successfully. Generating DOTS systems...followed by a normal C# compile of the generated assembly. - Peek into your Generated Directory (
Assets/SnivelerCode/AiBehavior/Generated):SystemsNote.g.csnow exists. (A bareSequence+Waittree needs no generated action systems โ those only appear when you use Find / Condition / Change-Entity / custom actions.)
Step 4 โ Set Up the Agent Entity
- Open a Sub-Scene (required for DOTS baking). If you don't have one yet: Window โ General โ Scene doesn't list sub-scenes โ create one via the Scene window's Sub Scenes section, or use Create โ Entities โ Sub Scene in the Project window.
- Create a new empty GameObject in that sub-scene, e.g.
AI Agent. - Add the
BtAgentAuthoringcomponent and drag yourMyFirstAgentgraph into its Tree field. - (Optional) Add
BtSettingsAuthoringto any GameObject in the sub-scene to tune the runtime:- Max Iterations Per Frame (default
50) โ the per-agent node-step budget per frame; raise it for very deep trees (see Runtime Internals). - Log Infinite Loop Warnings (default on) โ logs an error when an agent hits the budget.
- Max Iterations Per Frame (default
โ ๏ธ Baking requirements for
BtAgentAuthoring: the graph must not be empty and must have a root node. If the baker can't find a root you'll seeBtCompiler: Root node not found!in the Console. Also note the agent needs a transform (TransformUsageFlags.Dynamic) โ the baker always creates one.
Step 5 โ Bake and Play
- Make sure the sub-scene is closed (not open in a Scene view) so it bakes on Play.
- Press Play.
- Open Window โ General โ Entity Hierarchy (provided by the Entities package) and select your
AI Agententity. - With the Behavior Editor still open, it automatically switches to the graph running on the selected entity โ and you'll see the
SequenceandWaitnodes light up yellow (Running). After ~3 seconds they flash green (Success) as the tree completes and restarts.
That's the full loop: author โ compile โ bake โ observe live.
Next Steps
- Add a Blackboard variable and a
Blackboard Conditionto make the wait duration data-driven โ see The Blackboard System. - Build reusable chunks with Sub-Trees.
- Write your first
[BtCustom]C# action โ see Custom Nodes and The Custom Action Execution Model.
๐จ Interface Overview
The Behavior Editor is the central hub for authoring AI logic: Window โ Sniveler Code โ AI Behavior Architect. The window title is Behavior Editor. It is divided into three zones:
| Zone | Location | Contents |
|---|---|---|
| Top Toolbar | across the top | Active Tree โ an object field for the GraphAsset to open; Hierarchy breadcrumbs โ appear when you dive into Sub-Trees (Hierarchy โ Parent โ Child), clickable to jump back up |
| Settings Panel | left column | two stacked tabs โ Node Settings (inspector for the selected node) and Variables (the graph's blackboard variables) โ with the Compile button below them |
| Graph Canvas | right, main area | the infinite-grid node graph: pan/zoom, right-click or Spacebar to search & create nodes, drag-rectangle multi-select, standard copy/paste/undo |
๐ 1. The Top Toolbar
- Active Tree โ an
ObjectFieldforGraphAsset. Drag a graph here (or use the dropdown) to open it. The currently open graph is also restored automatically when you reopen the window (the last opened tree is remembered via PlayerPrefs). - Hierarchy breadcrumbs โ when you dive into Sub-Trees, the toolbar shows
Hierarchy -> Parent -> Child -> .... Click any previous crumb to jump back up; clicking the last item does nothing. Opening a root tree resets the breadcrumb trail.
๐ 2. The Settings Panel (Left)
A vertical panel with two stacked tabs plus the compile button:
- Node Settings tab โ acts as an Inspector for the currently selected node (the node type name is shown as a header). Each node type draws its own fields:
- numeric fields (
FloatField/IntegerField) for timers, counters, cooldowns, EnumFielddropdowns for policies and modes,- component pickers for Find / Condition / Change-Entity,
- the custom-action dropdown + generated parameter fields,
- prefab
ObjectFields where a node needs a prefab.
- numeric fields (
- Blackboard (Variables) tab โ manages the graph's named blackboard variables: name, type (
Bool/Int/Float) and default value. See The Blackboard System. - Compile button โ persists the graph and runs code generation (see Project Setup).
๐บ 3. The Graph Canvas (Right)
- Navigation: middle-mouse (or
Alt+ left-drag) pans, wheel zooms,Spacebar+ drag also pans. - Add nodes: right-click (or
Spacebar) opens the Node Search Window โ a grouped tree built from every[GraphNode]-registered node type. Search and click to create. The node is placed at the cursor position. - Selection: left-click a node to select it (its inspector appears in the left panel). Multi-select with drag-rectangle.
- Copy & Paste: standard
Ctrl+C/Ctrl+Vโ nodes are serialized to JSON, re-instantiated with fresh GUIDs, offset by (50, 50) andReset()is called (e.g. Change-Entity drops its stored target). Edges between copied nodes are not recreated โ reconnect them by hand. - Undo / Redo: every structural mutation is recorded against the graph asset (
Undo.RecordObject), soCtrl+Z/Ctrl+Shift+Zworks and the canvas rebuilds from the asset on undo. - Deleting: select and
Delete. Connected edges are removed with the node.
Ports: Flow vs. Data
Every node exposes two port families:
| Port family | Visual position | Type | Capacity | Meaning |
|---|---|---|---|---|
| Flow (logic) ports | top / bottom of the node | Flow | Input: single ยท Output: multi (composites) / single (decorators, leaves) | Execution order. The bottom port is always the child connection point. |
| Data ports | left / right of the node | the payload's CLR type (or a marker type) | single, mostly multi for outputs | Pass runtime data (Entity, float3, blackboard variables) between specific nodes. |
Data port compatibility is strictly by type: a port can only connect to another port of the same port type (e.g. Entity โ Entity, float3 โ float3, blackboard-variable โ blackboard-variable). Compatible targets are highlighted while you drag.
๐ Data ports are compile-time wiring. When you connect two data ports, the output port's hash is copied into the input port's stored hash. Both then resolve to the same blackboard slot at compile time โ the connection is not a runtime graph edge, it's a shared-memory index. See The Blackboard System for the full mechanism.
๐ Play Mode: Read-Only Mode
On Enter Play Mode the editor:
- saves the dirty graph asset,
- recompiles if Auto Compile On Save is on,
- locks the canvas: nodes can't be moved, ports are disabled, deletion is disabled (you'll get a warning if you try), the toolbar and variable panel are disabled, and the node inspector is cleared.
On Exit Play Mode the locks are released and all debug highlights are cleared. This prevents structural edits while the runtime is iterating over the blob.
๐พ Saving & Auto-Save
- Structural edits mark the graph asset dirty; the window flushes dirty assets to disk on a 0.5 s throttled tick (
BtGraphAutoSave.SaveInterval). - Entering Play Mode performs an unthrottled
AssetDatabase.SaveAssets()first, so the bake never reads stale in-memory graph data. - The graph view state (pan/zoom) is persisted into the asset (
GraphPosition/GraphScale) and restored on load.
๐จ Broken Nodes
If a node's stored type can't be resolved (e.g. you deleted a custom action type, or the graph was made with an older version), the canvas shows a red ErrorNode placeholder and the build logs a warning. For custom nodes, a missing component is also flagged in the inspector ("Component mismatch โฆ") with the stale type kept in the dropdown so you can swap it back. Broken custom nodes are skipped by the code generator โ they won't break your compile, but the graph won't behave as drawn until you fix them.
๐ Working with Sub-Trees
As AI logic grows, graphs become unwieldy. Sub-Trees let you encapsulate logic into smaller, reusable GraphAssets โ build an AttackBehavior once and drop it into every enemy type that needs it.
๐ Setting Up a Sub-Tree
- Create a new AI Graph asset (Create โ Entities โ Sniveler Code โ AI Graph), e.g.
Sub_MeleeAttack. - Open your main tree in the Behavior Editor.
- Add a Composites โ Composite Sub-Tree node.
- Select it and assign the
Sub_MeleeAttackasset in the Node Settings panel. The node's subtitle updates to the asset name.
At compile time the compiler inlines the sub-tree: it walks the sub-tree's root and flattens all of its nodes into the parent's flat node array (the Sub-Tree node itself acts as a transparent pass-through โ its child list becomes the sub-tree's root children). The final BtBlob is one flat structure; there is no per-frame "enter sub-tree" indirection.
๐งญ Navigating Sub-Trees
- Dive in: double-click the Sub-Tree node, or click Open Sub-Tree in its inspector. The editor loads the nested graph and the toolbar shows the breadcrumb trail (
Hierarchy -> Main -> Sub_MeleeAttack). - Go back: click a previous crumb in the toolbar.
- While viewing a sub-tree, the Variables tab shows the sub-tree's own variables โ blackboard variables are per-graph (see below).
โ ๏ธ Circular Dependency Protection
The compiler tracks a visited graph stack while flattening and refuses to inline a graph that is already on the stack:
[BtCompiler] Circular dependency detected! SubTree 'X' is already in the compilation stack. Skipping.
The editor additionally blocks the most common mistake directly: assigning a graph to itself via a Sub-Tree node logs Cannot assign a tree to itself! and reverts the field.
Note the check is by asset name โ two different assets with identical names in the project will trip the guard. Keep graph names unique.
๐ง Blackboards & Sub-Trees
Blackboard variables are per graph asset, and the compiler merges them when flattening:
- Every variable of every inlined sub-tree is registered into the same shared-state table as the parent's variables, keyed by the variable's hash (FNV-1a of a GUID assigned when you create the variable).
- Two variables with the same hash (i.e. literally the same variable, copy-pasted across graphs) collapse into one state slot โ that's how a sub-tree and its parent can read/write the same blackboard variable.
- Default values: each variable's authored default initializes its state slot at bake time. If parent and sub-tree both declare the same variable, the last initialization wins (sub-tree variables are registered before the parent's root is flattened).
๐ก Practical consequence: to share a variable between a parent tree and a sub-tree, the variable must exist (with the same identity) in both graphs. A variable that only exists in the sub-tree is private to it.
๐ Debugging Across Sub-Trees
In Play Mode the editor maps flattened node indices back to visual nodes โ including through sub-trees. When a node inside the open sub-tree is active, its visual node lights up; when the flat index belongs to a sub-tree that is not currently open, the editor also highlights the corresponding Sub-Tree node in the parent (so you can tell "the activity is inside that sub-tree" without diving in).
๐ Runtime Visual Debugging
Debugging DOTS is notoriously hard because the logic lives inside multithreaded Burst jobs. AI Behavior Architect mirrors the evaluator's state machine back into the editor so you can watch your exact graph run, node by node, in real time.
๐ How to Monitor an Agent
- Enter Play Mode (the editor auto-switches to read-only and locks the canvas).
- Open the Entity Hierarchy window (Window โ General โ Entity Hierarchy, provided by the Entities package).
- Select any entity that carries a
BtAgentcomponent. - If the Behavior Editor is open, it snap-loads the graph asset that the selected entity is running (resolved by matching the blob's
TreeHashagainst graph asset hashes) and begins polling that entity's debug state every editor frame.
๐ก Selecting a different agent switches the editor to that agent's tree. If two agents run the same graph, the editor shows the graph once and mirrors the status of whichever agent you selected last.
๐ฆ Visual Feedback
The Burst job writes each node's NodeStatus into an editor-only BtDebugState buffer (one slot per flat node); the editor reads the whole buffer every frame and applies it to the canvas:
| Border / port color | Meaning |
|---|---|
| ๐ก Yellow | The node is currently Running (it will be re-ticked next frame). |
| ๐ข Green | The node returned Success this frame. The highlight fades after ~0.5 s. |
| ๐ด Red | The node returned Failure this frame. The highlight fades after ~0.5 s. |
| โฌ Gray | Idle โ the node was not touched this frame. |
Terminal results (Success/Failure) are stamped with a timestamp and automatically fade to gray, while Running stays lit as long as the node keeps ticking โ so a Wait node glows yellow for its whole duration, and a fast Condition flickers green/red each frame.
Status reset semantics: when an agent's tree restarts (root completes and the index resets to 0), the runner flags DebugReset, and the editor resets every slot to None โ except slots flagged BlockReset (nodes that are mid-execution, like a running Parallel's active branch or a running Wait), which keep their state. This prevents stale "success" flashes when a tree loops.
For Parallel nodes, each running branch is logged into its own flat node, so you can see which branches of a parallel are still alive. When a Parallel finishes and abandons still-running branches, the abandoned custom actions are deactivated (their Tag disabled, see Runtime Internals) so they stop burning CPU.
โก Zero Overhead in Production
Does visual debugging slow down the DOTS jobs? No.
- The
BtDebugStatebuffer, theBtDebugInitSystemand everylogger.Log(...)call sit behind#if UNITY_EDITORand/or[Conditional("UNITY_EDITOR")]โ in a player build the compiler strips the calls entirely, leaving no buffer, no writes, no branching. - Editor-only warning/error logs go through
BtLoggerwith[Conditional("SNC_DEBUG_INFO")]/[Conditional("SNC_DEBUG_WARNINGS")]define gates, so even log formatting disappears unless you opt in by defining those symbols.
๐ก You can opt into managed logging in the editor for deeper diagnostics: define
SNC_DEBUG_INFO(info) and/orSNC_DEBUG_WARNINGSin your assembly's player settings or a scripting define.BtLogger.LogManagedandBurstLogBuilder.LogWarningonly emit under those defines.
๐ What to Look For (Common Debug Patterns)
- A node stuck yellow forever โ its action never completes. For custom actions: check that the agent actually has every component the
Processmethod queries (the generated job silently skips entities that don't match its query โ see The Custom Action Execution Model). - A Find node flickering red โ nothing in range matches the component conditions, or the Spatial Cell Size is smaller than your world's entity spacing (cells are only visited inside the search cube).
- Parallel looks "stuck" โ one branch is running a long action; the yellow branch child tells you exactly which one.
- Tree restarts every frame (whole root flashes) โ your root completes and the tree re-runs from the top; that's normal Behavior Tree behavior (root is ticked every frame), not a bug.
๐ง The Blackboard System
In Behavior Trees, nodes need a way to share data: a Find node locates an enemy, and a Move action needs to know where it is. AI Behavior Architect provides a two-tier data system โ both tiers are unmanaged, per-agent, allocation-free, but they serve different purposes and live in different buffers:
| โ Named Variables | โก Data Ports | |
|---|---|---|
| Buffer | DynamicBuffer<BtNodeState> | DynamicBuffer<BtBlackboardEntry> |
| Slot size | 4 bytes โ float union (float / int / bool / uint) | 16 bytes โ unmanaged union (any unmanaged type โค 16 bytes: float, int, double, float2, int2, float3, Entity, โฆ) |
| How created | by designers in the editor's Variables tab (name + type + default value) | automatically, one slot per unique connected horizontal port |
| Identity | the variable's hash โ FNV-1a of a GUID, assigned when the variable is created | the port's hash โ FNV-1a of a GUID, stored in the node data |
| Used by | Blackboard Condition / Blackboard Modify nodes; [BtBlackboard] parameters of custom actions | Find / Condition / Change-Entity / Create-Entity ports; [BtInput] / [BtOutput] parameters of custom actions |
โ Tier 1 โ Named Variables (BtNodeState buffer)
These are the variables you see in the Variables tab. Each variable is:
- Name (editor-only, for humans),
- Type โ
Bool,IntorFloat(this is the editor's interpretation; at runtime the slot is a 4-byte value union), - Value โ the default (stored as a float;
booluses0/1), - Hash โ FNV-1a of a random GUID, assigned when the variable is created. The hash is the variable's identity โ it's what gets compiled into the blob, not the name. Renaming a variable is free; deleting and re-adding it changes its identity.
At bake time the compiler registers every variable (including sub-tree variables) into a shared state table keyed by hash:
- each unique hash gets exactly one
BtNodeStateslot (GetOrCreateSharedState), - the variable's authored default value initializes that slot (
StateVariables), - nodes that reference the variable store only the slot's index, not the value.
So blackboard variables are just named, initialized slots in the node-state buffer โ reading or writing one is a single unmanaged array access inside Burst.
Where named variables are used
| Consumer | How it's wired |
|---|---|
| Blackboard Condition node | the inspector's Variable dropdown picks a variable โ the node reads its slot |
| Blackboard Modify node | same; writes back to the slot |
Blackboard Condition/Modifyoutput port ("Enable Output") | the port's payload is the variable's hash; connect it into a custom action's [BtBlackboard] input port |
Custom action [BtBlackboard] float/int/uint p (optionally ref) | resolved to the slot index via the connected port; ref writes back after Process |
โ ๏ธ
[BtBlackboard]โ[BtInput].[BtBlackboard]connects to named variables (4-byte slots,float/int/uintonly).[BtInput]connects to data-port channels (16-byte slots, any unmanaged type โค 16 bytes). They are different port types in the editor and cannot be connected to each other.
โก Tier 2 โ Data Ports (BtBlackboardEntry buffer)
Data ports are the horizontal connections. Each output port of a node (Find's Entity/float3, Create-Entity's Entity, a custom action's [BtOutput], a blackboard node's variable port) is assigned a port hash (FNV-1a of a GUID, generated once and stored in the node data). When you connect it to an input port, the input port stores the same hash.
At compile time the compiler walks every port hash and builds the buffer:
- every unique non-zero hash gets one
BtBlackboardEntryslot โ a 16-byte unmanaged union (BtBlackboardValue:float/int/bool/double/float2/int2/float3all overlay byte 0;Entityis 8 bytes), - the blob stores a
Hash โ slot indextable (Hashes+BbIndices), and each node that reads or writes a port stores only the slot index, - at runtime, the producing node writes the value with a typed helper (
buffer.SetValue<float3>(slot, value)), and the consuming node reads it with the matching type (buffer.GetValue<float3>(slot)).
๐ก Slots are shared by hash, not by connection. If two output ports ever carried the same hash they would share a slot โ which is exactly the mechanism that lets a
[BtOutput]port and a[BtInput]port exchange values: the output port's hash is copied into the input port at connection time, so both resolve to the same slot.
What can flow through a data port?
Any unmanaged type โค 16 bytes: bool, byteโฆint, float, double, float2, int2, float3, and Unity.Entities.Entity. The editor enforces type equality on connection, so a float3 port can only feed another float3 port. In generated code the value is bit-copied (UnsafeUtility.CopyStructureToPtr), which is why the 16-byte bound exists โ the slot is a 16-byte field.
Unconnected ports
An unconnected input port has hash 0, which compiles to slot index -1 ("no slot"):
[BtInput]on an unconnected port reads the slot's default value (zero for numbers,Entity.Nullfor entities) โ the read is bounds-checked and returns a type default.- An unconnected
[BtBlackboard]port logs an error at compile time (Custom node 'X' has an unconnected [BtBlackboard] port.) and compiles to slot-1. Create-Entitywith an unconnected position input uses its authored static position instead.
Lifetime & Reset
- Both buffers are created per agent entity at bake time, sized to the compiled graph (
NodeStateCountandBlackboardCount). - Values persist across frames and across tree restarts (they are not cleared when the root completes) โ that's what makes blackboard variables stateful.
- If you destroy and re-spawn the agent, it gets a fresh buffer initialized from the graph defaults.
Performance Note
In object-oriented frameworks, blackboards are typically Dictionary<string, object> โ allocation-heavy and unusable in Burst. Here:
- zero allocations โ everything is a pre-sized unmanaged buffer on the entity chunk,
- cache-friendly โ the buffer lives in the same chunk family as the agent's other components,
- type-stable โ slots are fixed at compile time; there is no runtime lookup by string, ever.
๐ Blackboard Nodes
Besides custom C# actions, you can read and write named blackboard variables directly with visual nodes. Both live under Blackboard/ in the search window.
โ๏ธ Blackboard Condition
Blackboard/Blackboard Condition โ a leaf gatekeeper. Reads one named variable and returns Success if the comparison holds, Failure otherwise.
Inspector:
| Field | Meaning |
|---|---|
| Variable | dropdown of the graph's named variables (by name; identity is the hash) |
| Operator | Skip, Equal, NotEqual, Greater, Less |
| Value | the static value to compare against (float field) |
| Enable Output | when on, the node grows a horizontal output port carrying this variable's hash โ connect it to a custom action's [BtBlackboard] input so the same variable flows through |
Runtime semantics (exact):
- The variable's 4-byte slot is read as a float and compared:
Equal/NotEqualuse a 0.001 absolute epsilon (|a โ b| < 0.001), not strict equality โ integer-valued floats work fine with it,Greater/Lessare strict,Skip(the default) never evaluates โ the condition always succeeds (it's the "not configured" state, not a failure state).
- The node is a terminal node: single input flow port, no output flow port.
Example: variable Health (Float). Set Health < 20 โ when the agent's health drops below 20 the condition succeeds and the tree can proceed to a Flee branch.
โ๏ธ Blackboard Modify
Blackboard/Blackboard Modify โ a leaf that changes a variable. Always returns Success once applied.
Inspector:
| Field | Meaning |
|---|---|
| Variable | the variable to modify |
| Operator | Skip, Set, Inc (add), Dec (subtract) |
| Value | the static value |
| Use DeltaTime | when enabled, Value is multiplied by DeltaTime before the operation (per-frame accumulation โ see below) |
| Enable Output | same output-port behavior as Condition |
Runtime semantics (exact):
- The slot holds one float; the operation is
current = Set ? value : current ยฑ (value ยท ฮt?)and written back in the same frame. Skipleaves the value untouched (still returns Success).- Because
int/boolvariables share the float slot, modifying them is done in float space โ e.g.Inc 1on a bool toggles 0โ1โ2โฆ; treatInt/Boolvariables as float-backed integers/flags.
The Use DeltaTime pattern
With Use DeltaTime on, each execution of the node applies value ยท ฮt โ i.e. it integrates real time. The node itself only runs when the tree reaches it, so to accumulate continuously you wrap it in an infinite Repeater (Repeater value 0):
Sequence
โโ Repeater (value 0 = infinite)
โโ Blackboard Modify (Inc, Value 1, Use DeltaTime โ)
โ variable increases by exactly 1.0 per real second
This is the idiomatic way to build a "time spent in state" counter.
โก Data-Port Outputs ("Enable Output")
Both nodes can expose their variable as a data port (the horizontal port on the right). The port's payload is the variable's hash, typed as the blackboard-variable marker type, so it can only connect to a [BtBlackboard] input port of a custom action:
Blackboard Modify (Health, Set, 100, Enable Output โ)
โ output (variable: Health)
โผ
Action Custom โ MoveAction.Process([BtBlackboard] ref float speed, โฆ)
At runtime the generated job reads the variable's state slot before Process, passes it (by value or ref), and โ for ref โ writes the slot back afterProcess returns. This is the only way to hand a named variable to C#; everything else goes through [BtInput]/[BtOutput] data channels (see The Blackboard System).
๐ณ Composites
Composite nodes are the structural backbone of a tree. They have an Input flow port (top) and a Multi Output flow port (bottom) โ you can hang any number of children, ordered left to right by their horizontal position on the canvas (the compiler sorts children by Position.x).
All composites below are implemented as an iterative state machine: the agent's current node index is persisted on the entity, and each frame the evaluator re-enters the tree exactly where it left off. A composite never "waits" โ it either descends into a child, or reports a terminal status to its parent.
โก๏ธ Sequence
Composites/Composite Sequence
Runs children left โ right, one at a time.
- Descend: when first entered, jumps to the first child.
- Child Success: advances to the next sibling (fresh state). No siblings left โ Success.
- Child Failure: immediately Failure (remaining children are not attempted).
- Child Running: suspends there; resumes next frame.
- Empty Sequence: returns Success vacuously.
Use case: a strict task list โ
Check Ammo โ Aim โ Fire. Any failed step aborts the whole sequence.
๐ Selector
Composites/Composite Selector
Runs children left โ right, trying each until one succeeds.
- Descend: first child.
- Child Success: immediately Success (remaining children skipped).
- Child Failure: tries the next sibling. No siblings left โ Failure.
- Child Running: suspends there; resumes next frame.
- Empty Selector: returns Failure (nothing to try).
Use case: prioritized fallback โ
Take Cover โ Shoot โ Flee.
๐ฒ Random Selector / Random Sequence
Composites/Composite Selector Random ยท Composites/Composite Sequence Random
Same policies as Selector/Sequence, but children are picked in a random, non-repeating order for each pass:
- the composite stores a visited bitmask (one bit per child, in left-to-right order) in its state slot,
- each pick draws a random child among the unvisited ones; the random is seeded from
hash(entityIndex, nodeIndex, frame), so different agents pick different orders and the order changes frame to frame, - when all children have been visited, the composite returns its terminal status (
Successfor Random Sequence,Failurefor Random Selector).
โ ๏ธ Limit: at most 31 children. The visited mask is a 32-bit int; the compiler asserts this at bake time (
Random selector/sequence node X has N children, max supported is 31).
Use case: non-repeating patrol point selection, varied taunt animations.
โธ Parallel
Composites/Composite Parallel
Executes all children simultaneously โ each child branch is ticked in the same frame, each with its own state (stored in the agent's BtParallelBranchState buffer, sized at bake time for every Parallel branch in the tree, including branches inside sub-trees).
Policy (inspector dropdown):
| Policy | Completes whenโฆ | Result |
|---|---|---|
| Require All Success (default) | any child returns Failure โ abort | Failure |
| all children finish (no failures) | Success | |
| Require One Success | any child returns Success โ abort | Success |
| all children finish with no success | Failure |
Abort behavior (exact): when the Parallel completes, every branch still Running is abandoned:
- each abandoned branch's running custom/Find/Condition action is removed from
BtActionState, - a deactivation request is queued so the dispatcher disables that action's Tag on this agent โ the abandoned action stops executing immediately (this is what
BtParallelDeactivationTestsverifies).
Branches that haven't been started yet are simply never started. When the Parallel is re-entered later, all branch states are reset to None and every branch starts fresh.
Use case: move while shooting; monitor threats while performing a task.
โ ๏ธ Resuming a Suspended Composite
Because the resume point is stored on the child, a composite only re-enters when its child reports a terminal status. Practical consequences:
- a
Sequencewhose child isRunningstays on that child next frame (the sequence itself is not re-ticked), - decorators like
Repeater/Retryre-enter their child with an explicit state transition (see Decorators), - this is why a tree that is entirely of immediate-completing leaves (conditions, blackboard ops) can run many nodes in a single frame โ bounded by Max Iterations Per Frame (default 50). Deep, always-completing trees may need a higher budget; see Runtime Internals.
๐ Decorators
Decorator nodes have exactly one child (single Input + single Output flow port). They sit above the child and alter when it runs, how many times, or how its result is reported.
๐ Repeater
Decorators/Decorator Repeater
Runs its child a fixed number of times, fully re-executing it on every iteration.
- Value (inspector, int, โฅ 0): number of full runs.
0= infinite. - On entry the loop counter resets to 0.
- After each child completion (Success or Failure) the counter increments; if
count < valuethe child is re-entered with a fresh (None) state, otherwise the Repeater returns Success to the parent. - While the child is mid-run, the Repeater is not in the tick path at all (the agent's resume point is the child) โ this is what makes re-entrance clean: every iteration starts from zero.
Use case:
Chop Tree 5 times. Thevalue 0+ aBlackboard Modify (Use DeltaTime)inside is the canonical time-accumulator pattern (see Blackboard Nodes).
๐ Retry
Decorators/Decorator Retry
Re-runs its child when it fails, up to a limit.
- Value (inspector, int): maximum total attempts (the child runs at most
valuetimes). - On entry the attempt counter resets to 0.
- Child Success โ Success to the parent.
- Child Failure โ
attempts++; ifattempts < valuethe child is re-entered, otherwise Failure to the parent.
โ ๏ธ Known limitation โ custom/composite children can hang (verified against
BtRunnerSystem). On the retry re-entry the child is resumed inRunningstate, and the resume point stays on the child. Each node type handles aRunningre-entry differently:
Wait/Delayโ correct: their handlers treatRunningas "continue my timer", soRetry โ [Wait, then attempt]works as expected.- Custom actions (
Requested/Transaction) โ hang: the child's failure already removed itsBtActionStateentry, and theRunningre-entry path inProcessCustomActiononly observes an existing state โ with none present it does not re-enqueue the request. The agent then sleeps forever on that node (permanentRunningin the debugger).- Composites (
Sequence/Selector/random variants) โ hang the same way: they have noRunningre-entry case at all.Workarounds for retry semantics around custom logic:
- make the custom action retry internally โ it re-runs
Processevery frame whileRunning, so implement attempt counting inside the action, or- use
Selector โ [attempt-branch, โฆ]with the attempt counter in a blackboard variable, or- wrap the attempt in a
Repeateronly if the attempt is built from stateful leaves (same limitation applies to composites/custom actions).
Use case:
Try to unlock the door up to 3 times(with aWaitbetween attempts works out of the box).
โณ Cooldown
Decorators/Decorator Cooldown
Gates its child with a real-time cooldown measured against SystemAPI.Time.ElapsedTime.
- Value (inspector, float, seconds).
- The state slot stores a ready-time in milliseconds (
uintview of the float slot). - On entry: if
now โฅ readyTimeโ descend into the child; otherwise โ Failure immediately (the child is not ticked). - After the child completes โ with Success or Failure โ the ready time is set to
now + value, and the child's result is passed through unchanged.
Use case: prevent an enemy from spamming a heavy attack; rate-limit a projectile spawn.
Note: a child that is interrupted without a terminal status (e.g. abandoned by a Parallel) does not arm the cooldown โ only completed runs do.
๐ซ Inverter
Decorators/Decorator Inverter
Inverts the child's terminal status:
- child
Successโ Failure - child
Failureโ Success - child
Runningโ keeps running (inversion happens on completion)
Use case:
NOT in rangeโ wrap an in-range condition.
โ Force Success / โ Force Failure
Decorators/Decorator Force Success ยท Decorators/Decorator Force Failure
Run the child, discard its result, and report a fixed one:
- Force Success: always reports Success (even if the child failed).
- Force Failure: always reports Failure (even if the child succeeded).
The child is still fully executed โ these decorators change signaling, not execution.
Use case: fire a "best effort" animation trigger you don't want to block the branch on; or short-circuit a branch the moment a non-critical side effect completes.
โฑ Action Nodes
The built-in action leaves under Actions/ in the search window are the two time primitives. Both are terminal nodes (single Input flow port, no Output flow port) and both are stateful โ their timer lives in the agent's BtNodeState buffer, so they survive frame-to-frame without any external help.
โฑ Wait (time-based)
Actions/Action Wait
- Value (inspector, float, seconds). Default 1.
- On first entry: the timer is loaded with
Valueand the node reports Running. - Each frame:
timer -= DeltaTime(the simulation frame's delta, i.e. it respects time scaling), the timer is stored back, and the node stays Running whiletimer > 0. - When
timer โค 0โ Success.
Because the timer persists in the state slot, a Wait interrupted by a Parallel abort and later resumed continues from where it left off โ it never "jumps" on time-scale changes, it simply integrates ฮt.
โธ Delay (frame-based)
Actions/Action Delay
- Value (inspector, int, frames). Default 1.
- On first entry:
targetFrame = CurrentFrame + Valueis stored (theintview of the state slot) and the node reports Running. - Each frame: if
CurrentFrame โฅ targetFrameโ Success, otherwise keep running.
Wait vs. Delay โ which to use?
| Wait | Delay | |
|---|---|---|
| Unit | seconds (float) | frames (int) |
| Time scaling | scales with DeltaTime (slow-mo stretches it) | frame-locked โ always exactly N frames regardless of FPS |
| Precision | sub-frame (completes mid-frame) | whole frames |
| Use when | game-time durations (cooldowns, animation sync) | frame-exact timing (deterministic step patterns, per-N-frames behavior) |
โ ๏ธ Under a fixed-timestep simulation both behave as described.
Delayis the choice when you need deterministic cadence (e.g. "every 30 frames" for LOD checks or animation steps) because frame count is stable even when frame time isn't.
๐ Notes
- A
Wait/DelaywithValue โค 0completes on the next evaluation (Wait:timer โค 0immediately; Delay:targetFrame โค nowimmediately). - Neither node has a data port โ they are pure flow primitives.
- Both are the safe children for
Retry(see the Retry caveat in Decorators).
๐ Queries & Transactions
These nodes reach outside the agent and into the DOTS world. They are the only built-in nodes that require generated systems (a unique Find/Condition/Transaction configuration compiles into its own Burst system โ see Core Concepts).
๐ Component eligibility โ read this first. The Components Setup dropdowns in Find / Condition / Change-Entity only list component types tagged with the
[BtCondition]attribute:using SnivelerCode.AiBehavior.Runtime.Attributes; using Unity.Entities; [BtCondition] public struct PlayerTag : IComponentData { } [BtCondition] public struct HealthComponent : IComponentData { public float Value; }Tagging a struct does two things: (1) the editor lists it in the dropdowns, and (2) the Roslyn generator emits
Compare/Modifyextension methods for it โ the field-level condition/transaction evaluators the generated systems call. Supported field types arebool,sbyte/byte,short/ushort,int/uint,float, and enums. Untagged components (e.g.LocalTransform) can't be used here โ but they can be used in custom actions, which use a different mechanism (see ECS Components in Custom Nodes).
๐ Query Find (spatial search)
Queries/Query Find โ a terminal node that queries the world for entities matching component conditions within a radius of the agent, using a per-system spatial hash.
Inspector:
| Field | Meaning |
|---|---|
| Find Method | First (fastest), Nearest (closest match), Random (uniform random match) |
| Max Distance | search radius (world units). Distance check is a true sphere around the agent. |
| Spatial Cell Size | edge length of the hash cells (also part of the node's hash โ changing it generates a new system) |
| Complexity | read-only estimator: min(100, round(2 ยท (Distance/Cell)ยณ)) โ the approximate number of cells scanned |
| Components Setup | one or more [BtCondition] components, each with per-field conditions (operator dropdown per field: Skip/Equal/NotEqual/Greater/Less + value) |
Data ports (outputs):
| Port | Type | Content |
|---|---|---|
Entity | Entity | the found entity (written to the port's blackboard slot) |
float3 | float3 | the found entity's world position (LocalToWorld.Position) |
Both ports are multi-capacity โ fan them out to any number of consumers.
How the generated system works (per frame, per agent with a running Find):
- Collect job โ one
IJobChunkover all entities that have all required components and aLocalToWorldtransform: each is inserted into aNativeParallelMultiHashMap<int3, Result>keyed byfloor(position / CellSize).Resultcarries the component values, the entity, and its position. - Filter job โ for the agent: walks every cell of the cube
[pos โ r, pos + r](a cube, not a sphere โ the sphere only filters afterwards), and for each resident:- computes
distSqto the agent and rejects beyondrยฒ, - evaluates each component's conditions via the generated
Compare(buffer components: any element matching the conditions qualifies), - applies the mode:
Firstโ stop at the first match (gotoout of the cell loops);Nearestโ keep the smallestdistSq;Randomโ reservoir-style: replace the current pick with probability1/candidates(uniform over all matches), - on a match: writes
Entityandfloat3into the agent's blackboard slots and sets the action Success; otherwise Failure.
- computes
Tuning tips:
- Cell size โ typical entity spacing. Too small โ many empty cells visited; too large โ each cell holds many entities you must compare. The Complexity field is your at-a-glance cost meter.
- The search cube means the worst case is
(2r/cell)ยณcell lookups; keepMax Distancetight for dense worlds. - Both sides need a transform. The collect job only sees entities that have all required components and a
LocalToWorldtransform โ entities without a transform are invisible to Find. And the agent itself must have a transform (its position is the search origin);BtAgentAuthoringbakes one automatically. - Find results are point-in-time: the found entity is stored in the blackboard โ subsequent nodes should treat it as data, not a live reference (the entity may die; nodes that read it should handle
Entity.Null/non-existent gracefully โ custom actions can checkEntity.Existsโฆ note: existence checks require a component lookup; the simplest robust pattern is aConditionnode against a tag component).
๐งพ Query Condition (entity check)
Queries/Query Condition โ a terminal node that checks components on a target entity.
Inspector: same Components Setup as Find, but without distance/cell settings (no spatial search โ direct lookups).
Data ports: one Entity input (left). When connected (e.g. from a Find's Entity output), the check runs against that entity. When unconnected, it runs against the agent itself (the node's subtitle shows Self vs Entity).
Runtime: for each configured component: the target must have the component and it must match the field conditions (buffers: at least one element must match). All components must pass โ Success, anything missing or mismatched โ Failure.
Use case:
Find nearest chest โ Condition: ChestTag on it โ โฆor the self-checkCondition: MyStatus == Deadas a tree root gate.
๐ Action Change Entity (transactions)
Actions/Action Change Entity โ modifies component data on a target entity via generated transaction systems. This is the only built-in node that writes world state.
Inspector:
| Field | Meaning |
|---|---|
| Entity input port | target; unconnected = the agent itself (subtitle Self/Entity) |
| Components Setup | [BtCondition] components to modify; each field gets a transaction operator dropdown: Skip / Set / Inc (add) / Dec (subtract) + value |
Runtime semantics (exact, per component):
- Regular components (
IComponentData): the target must have the component (missing โ node Failure). Each field with a non-Skipoperator is applied through the generatedModifyโ with range clamping: integer fields that would overflow their type (e.g.Incpastint.MaxValue) make the whole transaction fail and the value is left untouched. - Buffer components (
IBufferElementData): the node also shows a Conditions list per component (in addition to the transaction list). At runtime it finds the first element matching the conditions and applies the transactions to it. If no element matches, a new element is appended โ this is also how you grow buffers. Implementation note: the fresh element is first run through the component's condition operators in modify-space and then through the transaction operators; with the common setup (condition operators left atSkip, i.e. "match any element") the condition pass is a no-op and the transactions simply apply to element 0 or to the appended element. If the target has no such buffer at all โ Failure. - All modifications go through a generated transaction system driven by a per-frame request queue (
BtTransitionRequest), applied via component/buffer lookups in a deferred job โ so writes are batched per frame and safe under parallelism. The node completes as soon as the system reports the result back.
Use case: damage application (
Health.Dec 10on a found target), toggling tags (Set), growing per-entity buffers.
โ ๏ธ Transactions modify data only โ adding/removing components and destroying entities are structural changes and require custom actions with anEntityCommandBuffer(see Entity Command Buffers).
๐ฃ Query Create Entity (spawn)
Queries/Query Create Entity โ spawns a baked prefab at runtime.
Inspector:
| Field | Meaning |
|---|---|
| Entity | the GameObject prefab to spawn. Its asset GUID hash is the node's identity โ swapping the prefab regenerates the system's registry entry. The prefab is automatically registered into the scene's global prefab registry at bake time (no manual step). |
| Enable Transform | when on: the spawned entity is placed at the Position (static float3 field, or from the float3 input port when connected) โ and the position input port exists only while this toggle is on |
| Parent to Agent | (requires Enable Transform) parents the spawn to the agent and links it into the agent's LinkedEntityGroup, so destroying the agent destroys the spawn |
| Enable Output | grows an Entity output port carrying the spawned entity (see timing note below) |
Runtime: the node reports Running the frame it's entered and enqueues a spawn request; BtSpawnSystem (running after the runner, same frame) dequeues all requests, sorts them by entity index for determinism, and instantiates via an EndSimulationEntityCommandBuffer. The node reports Success when the prefab resolves โ or Failure if the prefab is missing from the registry (e.g. the prefab was assigned but never baked into any scene's registry).
Output port timing: the spawned entity id is delivered through a one-frame relay โ the spawn system tags the new entity with a BtSpawnEntityMarker, and the next frame's Initialization group (BtSpawnBlackboardSystem) copies the entity into the output's blackboard slot and removes the marker. Treat the output as valid from the frame after the spawn.
Use case: spawn a projectile at a target position (Find โ
float3โ Create Entity), or spawn minions parented to the caster.
๐ป Custom Nodes
While AI Behavior Architect ships powerful built-in nodes, its real strength is how little code you write to add your own DOTS logic. You write a plain partial struct with one method; the framework's generator writes the entire ECS boilerplate around it โ the ISystem, the entity query, the IJobChunk, the blackboard plumbing, the delta-time injection, the command-buffer wiring โ and Burst-compiles it.
Step 1 โ Write the Struct
Create a C# script anywhere in your project (any assembly that the generated assembly can reference โ see Project Setup):
using SnivelerCode.AiBehavior.Runtime.Attributes;
using SnivelerCode.AiBehavior.Runtime.Components;
namespace MyGame.AI
{
// The string is cosmetic โ it shows up as the node's subtitle in the canvas.
// The node's *identity* is the fully-qualified struct type name, hashed (FNV-1a).
[BtCustom("Debug/Log Action")]
public partial struct LogAction
{
// The generator will call this private method inside the generated Burst job.
// It MUST be named "Process" and MUST return NodeStatus.
private NodeStatus Process()
{
// This runs inside a Burst job โ use the Burst-safe logger,
// not UnityEngine.Debug.Log (which is stripped/unsafe under Burst).
BtLogger.BurstLog()
.Append("Hello from Burst! ")
.Append(42)
.Log();
return NodeStatus.Success;
}
}
}
The three rules
partial structโ the generator declares the other half of the struct (as anIJobChunk) in your namespace. Forgettingpartialis the #1 cause of confusion.[BtCustom("โฆ")]on the struct โ registers the type with the editor's search window and with the Roslyn generator.- A
private NodeStatus Process(...)method โ any access level works as long as it's namedProcess; it must returnNodeStatus. Any other return type produces compiler error BA0001 ("The Process method must return NodeStatus").
Step 2 โ Find It in the Editor
Save the script, wait for Unity to compile, then:
- Open the Behavior Editor โ right-click /
Spacebarโ search window. - Pick Actions โ Action Custom โ the node's inspector shows a dropdown of every
[BtCustom]type in the project (displayed asNamespace/StructName), plus one field per[BtParam]parameter. - Pick your type from the dropdown. The node is now a fully functional DOTS action.
If the dropdown says "No actions found", your assembly isn't compiled yet, or the type lacks [BtCustom]. If a previously-used type disappears from your graph, the node renders broken (red border, "Component mismatch" in the inspector) โ re-selecting another action fixes it.
Step 3 โ What the Generator Produces
For MyGame.AI.LogAction (hash H = FNV-1a of "MyGame.AI.LogAction") the Roslyn generator emits, in your namespace:
// <auto-generated>
namespace MyGame.AI
{
// The ISystem: builds the query, updates handles, schedules the job
public partial struct Bt{H:X}System : ISystem
{
public struct Tag : IComponentData, IEnableableComponent { }
// โฆ queries, type handles, OnCreate / OnUpdate โฆ
}
// The other half of YOUR struct: a Burst-compiled IJobChunk
[BurstCompile]
public partial struct LogAction : IJobChunk
{
private const ulong ACTION_HASH = H;
public ComponentTypeHandle<Bt{H:X}System.Tag> TagHandle;
[ReadOnly] public ComponentTypeHandle<BtAgent> AgentHandle;
public BufferTypeHandle<BtActionState> ActionStates;
// โฆ one handle per Process() parameter that maps to a query component โฆ
public void Execute(in ArchetypeChunk chunk, int chunkIndex,
bool useEnabledMask, in v128 chunkEnabledMask)
{
// for each entity whose Tag is ENABLED:
// for each BtActionState entry with ActionHash == H and Status == Running:
// var status = Process( /* parameters resolved below */ );
// state.Status = status;
// disable the Tag on entities left with no running H-action
}
}
}
and the SystemNodes registry (written by the editor) adds new BaCustom { Index = H, Components = new[] { "MyGame.AI.LogAction" } } so that:
BtBakingSystem(bake time) adds a disabledBt{H:X}System.Tagto every agent entity whose tree contains this action โ the Tag is the per-agent "I have (or will have) this action" marker,BtDispatcherSystem(runtime) enables/disables that Tag on the agent when a node instance activates/deactivates,- the action system's job iterates only agents with the Tag โ and only entities whose entire query matches (see the execution model below).
๐ก Two generated systems per hash โ never per node instance. Ten agents using the same action share one system; a node's instance is identified at runtime by
(ActionHash, NodeIndex)inside the agent'sBtActionStatebuffer, so the same action type can run concurrently at different tree positions on the same agent.
Step 4 โ Reading the Result Back
Return values have fixed meanings (they become the node's NodeStatus):
| Return | Meaning |
|---|---|
NodeStatus.Running | keep ticking โ Process is called again next frame (this is how you build stateful actions: timers, movement, waiting) |
NodeStatus.Success | completed successfully โ the node reports Success to its parent |
NodeStatus.Failure | failed โ the node reports Failure to its parent |
A full, realistic example with input ports, parameters, component access and delta time is in the next sections: The Custom Action Execution Model, API Attributes and ECS Components in Custom Nodes.
โฑ The Custom Action Execution Model
Custom actions (and the built-in Find / Condition nodes) do not run inside the tree evaluator. The runner requests them, and a dedicated generated system executes them in its own parallel job. Understanding this request โ execute โ read-back loop is the single most important thing for custom-node authors, because it explains the timing, the query rules, and the most common "my action never runs" bug.
The Frame-by-Frame Timeline
Frame N
BtRunnerSystem (parallel over agents)
โโ node entered โ BtActionState{hash, nodeIndex, Running} added to the agent
BtNodeRequest{agent, nodeIndex, hash, Active=true} enqueued
BtDispatcherSystem (generated, after the runner)
โโ dequeues request โ EndSimulation-ECB: ENABLE <Bt{H:X}System.Tag> on the agent
(tag becomes effective at end of frame N)
Frame N+1
Bt{H:X}System (generated action system)
โโ IJobChunk over agents with Tag + full query match:
Process() is called; status written back into BtActionState
agents left without a Running H-action get their Tag DISABLED
BtRunnerSystem
โโ re-enters the node: reads BtActionState.Status
Running โ node stays Running
Success โ action state removed; node reports Success (and, if the
node has a flow child, descends into it)
Failure โ action state removed; node reports Failure
Consequences:
- One-frame activation latency.
Processfirst runs the frame after the node was entered; the runner observes the result the next time it runs (same frame if the action system runs before the runner in your world layout, one more frame otherwise). A "single-frame" action therefore occupies at least 2 frames: enter โ execute โ complete. Runningmeans "call me again". WhileProcessreturnsRunning, the Tag stays enabled and the action re-executes every frame โ no polling code needed, the loop is implicit.- Deactivation is automatic. When the action reports a terminal status, its
BtActionStateentry is removed and the Tag is disabled (no running actions left) โ the job stops visiting the agent entirely. Zero cost when idle. - Parallel abandonment. If a Parallel node finishes while your action is still
Running, the runner removes the state entry and queues a deactivation โ the Tag is disabled and your action stops mid-run. (YourProcessis not given a cancellation callback; it simply stops being called. Any side effects it made remain.)
The Query Rule (the #1 "my action never runs" bug)
The generated system builds one entity query from your Process signature:
WithAllRW<BtActionState, Tag>
.WithAll<BtAgent>
.WithAll<every IComponentData parameter> // WithAllRW when passed `ref`
.WithAll<every DynamicBuffer<T> parameter>
.WithAll(RW if [BtOutput] present)<BtBlackboardEntry>
.WithAll(RW if [BtBlackboard] ref present)<BtNodeState>
An agent entity is only visited if it matches the entire query. Therefore:
โ ๏ธ Every component and buffer you reference in
Processmust exist on every agent entity that can run this action. If an agent lacks even one of them, the entity silently falls out of the query:Processis never called, theBtActionStateentry staysRunningforever, the Tag stays enabled, and the agent's tree hangs on that node (watch for the permanent yellow border in the debugger).
Design guidance:
- Reference only components you are certain all your agents have (e.g.
LocalTransform, a sharedAgentDatastruct). - If you need to optionally touch a component, don't put it in the signature โ use a
ComponentLookup<T>field andHasComponent/TryGetComponentinsideProcess(lookups are exempt from the query โ see ECS Components in Custom Nodes). - If different agent types need different actions, that's the point: give each type its own
[BtCustom]action (or gate with aConditionnode before the action).
State, Identity and the Tag
- The Tag is added at bake time by the generated
BtBakingSystemto every agent carrying aBtActionBakeRequestfor the hash (i.e. every agent whose compiled tree contains the node). It starts disabled and is toggled at runtime. - If you change which agents use an action, re-bake.
- The action identifies its node instances by
(ActionHash, NodeIndex): the same action type can run at several positions in one tree simultaneously, each with an independentBtActionStateentry. - Blackboard ports are resolved per node instance from the blob (
HashIndexโBbIndices), so two instances of the same action in the same tree can read/write different blackboard slots.
Performance Characteristics
- Idle cost: zero. No Tag enabled โ the action system's query is empty for that agent; the job doesn't even schedule over it (
_query.IsEmptyโ return). - Active cost: one
IJobChunkinvocation per entity per frame whileRunningโ same order of magnitude as any other ECS system job, Burst-compiled, no allocations. - Burst constraints apply to your
Processbody: no managed allocations, no string ops (useBtLogger'sFixedStringbuilder), noUnityEnginetypes except those explicitly allowed. UseUnity.Mathematicsfor math.
๐ท API Attributes Reference
All attributes live in SnivelerCode.AiBehavior.Runtime.Attributes. The Roslyn generator reads them from your Process signature and from your struct fields, and the editor reads the same metadata to draw ports and inspector fields.
Parameter Attributes
[BtParam] โ static, designer-tunable value
private NodeStatus Process([BtParam] float speed, [BtParam] bool aggressive) { }
- Exposes a field in the node inspector (no port).
- Supported types:
int,float,bool, and enums (rendered as a dropdown; stored as their int value). - Stored in the blob's pooled
FloatData(bools as0/1) and cast back at the call site. - Values are per-node-instance โ two instances of the same action in one tree can have different params.
[BtInput] โ dynamic value from a data-port channel
private NodeStatus Process([BtInput] float3 targetPosition) { }
- Generates a horizontal input port (left side) typed with the parameter's type.
- Any unmanaged type โค 16 bytes:
bool, integral types,float,double,float2,int2,float3,Entity. - At runtime the value is read from the agent's
BtBlackboardEntryslot that the connected output port writes to. Unconnected โ the slot's default (zero /Entity.Null). - Read-only inside
Process.
[BtOutput] โ dynamic value to a data-port channel
private NodeStatus Process([BtOutput] ref float3 currentPosition) { }
- Generates a horizontal output port (right side); connect it to
[BtInput]ports of other nodes. - Must be declared
refโ the generated code passes a local, reads your write-back, then stores it into the blackboard slot afterProcessreturns. - Same type rules as
[BtInput]. - Multiple
[BtOutput]parameters are allowed (one port each, in declaration order).
[BtBlackboard] โ named blackboard variable (4-byte slot)
private NodeStatus Process([BtBlackboard] float health) { }
private NodeStatus Process([BtBlackboard] ref float health, [BtBlackboard] int state) { }
- Connects to a named blackboard variable (created in the Variables tab, exposed via a Blackboard Condition/Modify node's Enable Output port). Port type is the blackboard-variable marker โ it cannot be connected to
[BtInput]/[BtOutput]ports. - Supported types:
float,int,uintonly (these map to theBtNodeStateslot'sValue/IntValue/UIntValueviews). Any other type is a generator error. - With
ref: the slot is written back afterProcessโ this is the only way to mutate a named variable from C#. - Multiple
[BtBlackboard]parameters are allowed; each needs its own connected port.
[BtEntityIndex] โ the agent's deterministic sort key
private NodeStatus Process([BtEntityIndex] int index, in Entity self) { }
- Injects the entity's index in the generated system's query (computed via
CalculateBaseEntityIndexArrayAsyncโ the same array you pass toEntityCommandBuffer.ParallelWritermethods). - Required for deterministic ECB usage: always pass it as the
sortKey(see Entity Command Buffers). - At most one per
Process.
[BtPrefab] โ prefab resolved from the global registry
private NodeStatus Process([BtPrefab] Entity projectile) { }
- Parameter type must be
Entity. At most one per action (a second is a generator error). - The node inspector grows a prefab
ObjectField; its asset GUID hash is stored with the node and the prefab is automatically registered into the scene's global prefab registry at bake time. - At runtime the parameter receives the baked prefab entity (via
BtUtils.GetPrefab), so you canCommandBuffer.Instantiate(i, projectile)โ noBtSpawnEntitynode needed. - Unassigned prefab โ generator/editor error at authoring time; missing at runtime โ
Entity.Nullis passed.
Bare (unattributed) Parameters
| Parameter shape | Interpretation |
|---|---|
Entity e (no attribute) | The agent's own entity (entities[i]) |
in T comp / ref T comp where T : IComponentData | Query component โ added to the system query; passed by value / by reference (see ECS Components in Custom Nodes) |
DynamicBuffer<T> buffer where T : IBufferElementData | Query buffer โ added to the query; element access via buffer[i]โฆ (pass by value; write elements back explicitly) |
A type matching a [BtSingleton] field | the singleton's component data (by value) |
anything else (e.g. a bare float with no attribute) | silently receives default โ the generator has no mapping for it and passes default. If a parameter mysteriously arrives as zero/null, check that it carries the right attribute |
Field Attributes
[BtDeltaTime]
[BtDeltaTime] public float DeltaTime;
- On a struct field (typically
float). The generatedOnUpdateassignsstate.WorldUnmanaged.Time.DeltaTimeto it before scheduling the job โ the sim's frame delta, exactly what your movement code wants.
[BtCommandBuffer(typeof(SomeSystem))]
[BtCommandBuffer(typeof(EndSimulationEntityCommandBufferSystem))]
public EntityCommandBuffer.ParallelWriter CommandBuffer;
- Field type must be
EntityCommandBuffer.ParallelWriter. - The generated system fetches the named system group's singleton each frame and calls
CreateCommandBuffer(state.WorldUnmanaged); the ParallelWriter is handed to your job. - Typical choice:
EndSimulationEntityCommandBufferSystem(structural changes replayed at end of frame).
[BtSingleton(typeof(MarkerComponent))]
[BtSingleton(typeof(WorldConfig))]
public WorldConfig Config;
- Any field type. The generated system queries the world singleton with the marker type you pass in the attribute and passes the field's type component data into
Process(by value). Use this to reach any world singleton withoutSystemAPI(which isn't available in jobs).
ComponentLookup<T> / BufferLookup<T> fields
public ComponentLookup<LocalTransform> Transforms; // read/write
[ReadOnly] public BufferLookup<ScoreBuffer> Scores; // read-only
- Exempt from the query โ the system compiles even if your agents don't all have
T. InsideProcessuseHasComponent,TryGetComponent,TryGetBuffer,[entity], โฆ for random access. This is the correct tool for targeted access (e.g. modifying the entity a Find node located).
The Hash Layout Inside the Blob
For an action node the compiler stores, starting at the node's HashIndex:
[ nodeHash (identity) ] [ prefabHash (only if [BtPrefab] used) ] [ inputPortHash_0 ] [ inputPortHash_1 ] โฆ [ outputPortHash_0 ] โฆ
nodeHash= FNV-1a of the fully-qualified struct name (matches the generated system'sACTION_HASH).- Port hashes resolve through the blob's
Hash โ BbIndicestable into blackboard slots;0/-1means "unconnected โ default". - The editor keeps this layout in sync with your
Processsignature when you change the component type of an existing node: surviving ports keep their hashes, stale entries are dropped, new ports start unconnected.
Error Codes You May See
| Code | Meaning |
|---|---|
| BA0001 | Process doesn't return NodeStatus (or is missing) |
| BA0002 | generation failure โ invalid type parse, no valid components for a registered system, or [BtBlackboard]/[BtPrefab] with an unsupported type |
| BA0003 | warning: a component type in a generated system's Components array couldn't be resolved in the project (usually a typo in a [BtCondition] component name, or the assembly isn't referenced) |
๐ ECS Components in Custom Nodes
You do not need to write SystemAPI.Query or manual ComponentLookup plumbing to touch ECS data from an action. How data flows depends on how you declare it โ and the declaration decides the query membership (see the query rule in The Custom Action Execution Model).
Reading Data โ in (by value)
private NodeStatus Process(in LocalTransform transform)
{
float3 currentPos = transform.Position;
return NodeStatus.Success;
}
T : IComponentDataas a bare (orin) parameter โ the generated query usesWithAll<T>and the job reads a read-only chunk array.- Cheapest access; the entity must have
T.
Writing Data โ ref
private NodeStatus Process(ref LocalTransform transform, [BtParam] float speed)
{
transform.Position.y += speed * DeltaTime;
return NodeStatus.Running;
}
ref Tโ query usesWithAllRW<T>and the job writes back through the chunk array (the generatedExecutere-storeshandleN[i] = valueafterProcess).- Same entity-must-have-
Trule.
Buffers โ DynamicBuffer<T>
private NodeStatus Process(DynamicBuffer<AnimatorParameterData> params)
{
var p = params[(int)index];
p.Value = value;
params[(int)index] = p; // element write-back is explicit
return NodeStatus.Success;
}
DynamicBuffer<T>(T : IBufferElementData) as a parameter โ queryWithAll<DynamicBuffer<T>>(norefneeded on the buffer itself).- Element access is copy-modify-write โ assign the element back, as in any ECS job.
- The buffer must exist on the agent (buffers added by baking, or via
AddBuffer).
Random / Targeted Access โ ComponentLookup & BufferLookup Fields
When you need to touch another entity (a Find result, a target from the blackboard) or a component you can't guarantee on every agent, declare a lookup field:
[BtCustom("Combat/Apply Damage")]
public partial struct ApplyDamageAction
{
// Exempt from the query โ agents may lack these components
public ComponentLookup<HealthComponent> Health;
[ReadOnly] public ComponentLookup<LocalToWorld> Positions;
private NodeStatus Process([BtInput] Entity target, [BtParam] float amount)
{
if (!Health.HasComponent(target)) return NodeStatus.Failure;
var health = Health[target];
health.Value -= amount;
Health[target] = health;
float3 pos = Positions[target].Position;
BtLogger.BurstLog().Append(pos).Log();
return NodeStatus.Success;
}
}
ComponentLookup<T>โ read/write; add[ReadOnly]to the field for a read-only lookup (smaller, safer, Burst-verified).BufferLookup<T>โ same idea forDynamicBuffer<T>;TryGetBuffer(entity, out var buffer).- Lookups give you
HasComponent/TryGetComponent/[entity]โ the idiomatic way to handle optional or foreign entities. - โ ๏ธ Lookups are not parallel-safe across entities the job hasn't "claimed": for the agent's own entity prefer query components (the chunk gives you safe access); for other entities you are responsible for access correctness (this is standard ECS job practice โ the generated job is a
ScheduleParallelIJobChunk, so respect the usual parallel-for rules).
The Agent's Own Entity
private NodeStatus Process(in Entity self, in LocalTransform transform) { }
A bare Entity parameter (no attribute) receives the agent's own Entity โ pair it with lookups to modify the self from outside the chunk, or pass it into ECB calls.
Component Eligibility Compared
| Mechanism | Which components | Query membership | Typical use |
|---|---|---|---|
in / ref parameter | any IComponentData (incl. engine types like LocalTransform) | required on the agent | the agent's own core data |
DynamicBuffer<T> parameter | any IBufferElementData | required on the agent | the agent's own buffers |
ComponentLookup<T> / BufferLookup<T> field | anything | not required | targets, optional components |
| Find / Condition / Change-Entity nodes | only [BtCondition]-tagged types | n/a (node systems) | visual world queries |
๐ก Rule of thumb: agent's own data โ parameters; someone else's data โ lookups; visual/declarative logic โ built-in query nodes.
๐ Entity Command Buffers (Structural Changes)
In DOTS you cannot add components, remove components, or destroy entities from inside a parallel job โ structural changes must go through an EntityCommandBuffer (ECB). AI Behavior Architect wires ECBs into custom actions with two attributes.
The Two Pieces
[BtCommandBuffer(typeof(<SystemGroup>))]on anEntityCommandBuffer.ParallelWriterfield โ tells the generator to create a command buffer from that system group's singleton each frame and hand you itsParallelWriter:
[BtCommandBuffer(typeof(EndSimulationEntityCommandBufferSystem))]
public EntityCommandBuffer.ParallelWriter CommandBuffer;
The group type you pass decides when the commands replay:
| Group | Replays | Use for |
|---|---|---|
EndSimulationEntityCommandBufferSystem | end of the simulation step | the default choice โ most structural changes |
BeginSimulationEntityCommandBufferSystem | start of the simulation step | changes that must be visible to this frame's systems |
PostPhysicsEntityCommandBufferSystem | after physics | physics-related structural changes |
any other โฆEntityCommandBufferSystem | at that group's replay point | specialized pipelines |
[BtEntityIndex]on anintparameter โ your deterministic sort key for the ParallelWriter methods.
Full Example
using SnivelerCode.AiBehavior.Runtime.Attributes;
using SnivelerCode.AiBehavior.Runtime.Components;
using Unity.Entities;
namespace MyGame.AI
{
[BtCustom("Combat/Destroy Self")]
public partial struct DestroySelfAction
{
[BtCommandBuffer(typeof(EndSimulationEntityCommandBufferSystem))]
public EntityCommandBuffer.ParallelWriter CommandBuffer;
private NodeStatus Process([BtEntityIndex] int index, in Entity self)
{
CommandBuffer.DestroyEntity(index, self); // deterministic replay order
return NodeStatus.Success;
}
}
}
โ ๏ธ Critical ECB rule: always pass the
[BtEntityIndex]value as the first argument (sort key) of the ParallelWriter method. The sort key is how Unity guarantees a deterministic replay order across threads โ omitting it (or using a non-deterministic one) can change simulation order from run to run on multi-core machines.
Spawning Prefabs from an Action
Combining [BtPrefab], [BtCommandBuffer] and [BtEntityIndex] gives you full dynamic spawning without any built-in spawn node:
[BtCustom("Combat/Spawn Projectile")]
public partial struct SpawnProjectileAction
{
[BtCommandBuffer(typeof(EndSimulationEntityCommandBufferSystem))]
public EntityCommandBuffer.ParallelWriter CommandBuffer;
private NodeStatus Process([BtEntityIndex] int index,
[BtPrefab] Entity projectile,
[BtInput] float3 position,
ref LocalTransform self)
{
var spawned = CommandBuffer.Instantiate(index, projectile);
CommandBuffer.SetComponent(index, spawned,
LocalTransform.FromPosition(position));
return NodeStatus.Success;
}
}
Remember the prefab must be assigned in the node inspector (it's registered into the scene's prefab registry at bake time, and resolved through it at runtime).
What You Can and Can't Do
| Operation | In a custom action? | How |
|---|---|---|
| Modify existing component data | โ freely | ref component params, or lookups |
| Add / remove / set components | โ | ECB (AddComponent, RemoveComponent, SetComponent) |
| Instantiate baked prefabs | โ | ECB (Instantiate) โ prefab via [BtPrefab] registry or any baked entity |
| Destroy entities | โ | ECB (DestroyEntity) |
| Create entities from scratch (new archetype) | โ | ECB (CreateEntity) โ though note: a fresh entity starts with no components; add them in the same buffer |
| Structural changes on the main thread during play | โ | never โ always ECB |
๐ก Change-Entity vs. custom actions: the built-in Action Change Entity node covers data modification (Set/Inc/Dec on component and buffer fields) with zero code. The moment you need structural changes (add/remove/destroy/spawn), you're in custom-action territory.
โ๏ธ Runtime Internals
This section documents the exact per-frame pipeline, the evaluator's state machine, and the runtime settings โ everything you need to reason about timing, ordering and performance.
The Frame Pipeline
All systems live in the Simulation group unless noted. "Generated" means produced by the code generator for your specific trees.
Initialization group (runs before simulation, every frame)
โโโ BtPrefabCacheSystem
โ keeps a persistent NativeHashMap<ulong,Entity> fed by the scene's
โ BtGlobalPrefabRegistry buffer; rebuilt only when the registry changes
โ (scene load). Consumed by BtSpawnSystem and [BtPrefab] action systems.
โโโ BtSpawnBlackboardSystem
for each entity carrying BtSpawnEntityMarker (set by BtSpawnSystem
last frame): copies the spawned Entity into the spawning agent's
blackboard output slot, then removes the marker.
โ Create-Entity output ports are valid from this frame on.
Simulation group
โโโ BtDebugInitSystem [UNITY_EDITOR only]
โ ensures every BtAgent has a BtDebugState buffer (via a parallel ECB job)
โโโ BtRunnerSystem โ
the tree evaluator
โ Burst IJobEntity over: BtAgent, BtActionState, BtParallelBranchState,
โ BtNodeState (+BtDebugState in editor), BtBlackboardEntry
โ โข reads BtRuntimeSettings once (max iterations, warnings)
โ โข ticks each agent's tree (see state machine below)
โ โข enqueues: BtSpawnRequest (Create Entity) and BtNodeRequest (actions)
โโโ BtDispatcherSystem [generated] [UpdateAfter BtRunnerSystem]
โ drains the BtNodeRequest queue, sorts by entity index (determinism),
โ then per request (parallel deferred job):
โ โข Find / Condition / custom action โ EndSimulation-ECB:
โ SetComponentEnabled<Bt{H:X}System.Tag>(agent, active)
โ โข Change Entity โ enqueues BtTransitionRequest into that
โ transaction system's own queue
โโโ Bt{H:X}System (one per unique Find / Condition / custom action)
โ Burst IJobChunk over agents whose Tag is enabled AND whose full
โ query matches; calls Process(); writes NodeStatus back into
โ BtActionState; disables the Tag on agents left with no running H-action
โโโ Bt{H:X}TransactionSystem (one per unique Change-Entity config)
โ drains its BtTransitionRequest queue, sorts by target index, applies
โ the Modify operations via lookups in a deferred job, and writes the
โ resulting status back into the agent's BtActionState
โโโ BtSpawnSystem [UpdateAfter BtRunnerSystem]
dequeues BtSpawnRequests, sorts by agent index (determinism), and in a
parallel deferred job: Instantiates the prefab (from BtPrefabCacheSystem's
map) via the EndSimulation-ECB, sets LocalTransform when "Enable
Transform" is on, optionally parents to the agent + LinkedEntityGroup,
tags the spawn with BtSpawnEntityMarker (for the output port), and
writes Success/Failure back into the agent (or its Parallel branch state)
Notes on ordering guarantees:
BtRunnerSystemโBtDispatcherSystemis explicit (UpdateAfter), so a node entered this frame can have its Tag enabled for this same frame's end (actions first run next frame).- Action systems vs. runner: there is no explicit ordering between the generated action systems and the runner (both in Simulation group). The design doesn't need one: the runner only reads
BtActionState, and actions only write statuses โ the handshake converges within one frame regardless of intra-frame order. - Spawn results:
BtSpawnSystemwrites the node's Success/Failure into the agent immediately (prefab resolution is synchronous against the registry map), so the tree sees the spawn as complete the same frame it was requested; only the entity id output waits for the Initialization relay.
The Evaluator State Machine
BtRunnerSystem schedules BtRunnerJob : IJobEntity (Burst). Per agent:
- Resume point: the agent's
BtAgent.CurrentNodeIndex(persisted component).-1means "tree finished" โ reset to0(re-run the root) and setDebugResetfor the editor. - Tick loop: a
whileloop steps the state machine; each iteration dispatches onNodeType(Sequence, Selector, Random variants, Parallel, Wait, Delay, Requested/Transaction, the six decorators, Blackboard Condition/Modify, SpawnEntity). After each step:- if the node completed and advanced to a parent/sibling, the loop continues (so an all-immediate tree can traverse many nodes in one frame),
- if the status is Running, the loop breaks โ the agent sleeps until next frame,
- the loop is capped at MaxIterationsPerFrame iterations; hitting the cap logs an error when warnings are enabled (see settings).
- Custom actions (
Requested/Transaction): the runner never runs them. It records aBtActionState{ActionHash, NodeIndex, Running}and enqueues aBtNodeRequest; on re-entry it reads the status the generated system wrote. Terminal statuses remove the state entry (and aSuccesson a node that has a flow child descends into it). - Parallel: each branch is an independent mini-state-machine stored in the
BtParallelBranchStatebuffer (its ownCurrentNodeIndex/LastNodeIndex/Status). On completion, abandoned branches get their running actions deactivated (see Composites). - Random composites: child picks are seeded from
math.hash(int3(entityIndex, nodeIndex, frame))โ deterministic per (agent, node, frame), different across agents.
Resume-point semantics in one sentence: the agent's current node is the deepest node that is not yet terminal โ everything above it is implied by the parent/child links in the blob, so a whole tree's progress fits in (CurrentNodeIndex, LastNodeIndex, LastStatus) plus the small state buffers.
Runtime Settings (BtRuntimeSettings)
Add BtSettingsAuthoring (MonoBehaviour, in a sub-scene) to configure the runner; it bakes into a world singleton BtRuntimeSettings:
| Field | Default | Meaning |
|---|---|---|
MaxIterationsPerFrame | 50 | per-agent cap on node-transitions per frame (the "infinite loop" guard). A well-behaved tree typically uses far less; a tree of always-completing leaves (conditions, blackboard ops) that runs to completion in one frame consumes one step per node โ raise this for very deep trees. |
LogInfiniteLoopWarnings | true | when an agent hits the cap, log Behavior Tree infinite loop detected on entity: โฆ (error). |
If the singleton is absent, the defaults above apply. The runner reads the settings lazily on its first update.
What "Zero Allocation" Means Here (Precisely)
- Hot path (per frame, per agent): the runner touches only the blob (read-only), the agent's unmanaged buffers, and two
NativeQueueparallel writers (fixed capacity, allocated once). Nonew, no strings, noList/Dictionary. - Find systems allocate one
NativeParallelMultiHashMapper system per frame (size = candidate entity count,TempJoballocator, disposed after the jobs) โ this is unmanaged, job-allocator memory, not GC; it's the price of the spatial index and scales with world entity count, not agent count. - Transaction systems allocate their queue/list once (
PersistentinOnCreate). - Editor-only paths (
BtDebugState, log formatting under debug defines) vanish in builds. - Logging:
BtLogger.BurstLog()builds messages in a 512-byteFixedStringand is[BurstDiscard]+Conditionalโ zero cost unless a debug define is active.
๐ Blob Layout Reference
The compiled tree is a BlobAssetReference<BtBlob> โ one contiguous unmanaged block. This is the exact layout the runtime walks, as produced by BtCompiler.Compile and baked by BtAgentAuthoring.
BtBlob โ Root
public struct BtBlob
{
public int BlackboardCount; // slots in the agent's BtBlackboardEntry buffer
public ulong TreeHash; // FNV-1a of the graph asset's GUID (editor identity link)
public BlobArray<BtNode> Nodes; // flat node table
public BlobArray<BtNodeData> NodeData; // per-node data offsets (sparse)
public BlobArray<float> FloatData; // pooled static floats (params, timers, positions)
public BlobArray<BtCondition> Conditions; // pooled condition/transaction tables
public BlobArray<BtParallel> Parallels; // parallel node settings
public BlobArray<short> ParallelChildren; // parallel branch child indices
public BlobArray<ulong> Hashes; // pooled hashes (node identity, prefab, ports)
public BlobArray<short> BbIndices; // hash โ blackboard slot (Tier 2 data ports)
public BlobArray<short> StateIndices; // [BtBlackboard] port hash โ state slot (multi-port nodes)
public short NodeStateCount; // slots in the agent's BtNodeState buffer
}
BtNode โ Flat Node Table
public struct BtNode
{
public NodeType Type; // Sequence | Selector | SelectorRandom | SequenceRandom |
// Waiting | Delay | Requested | Transaction |
// DecoratorCooldown | DecoratorInverter | DecoratorForceSuccess |
// DecoratorForceFailure | DecoratorRetry | DecoratorRepeater |
// Parallel | SpawnEntity | BlackboardModify |
// BlackboardCondition | SubTree (never appears in the flat table)
public byte ChildCount; // max 31 (bitmask limit, enforced at compile)
public short ParentIndex; // index into Nodes; the SubTree node is transparent
public short NextSiblingIndex; // -1 = last child
public short FirstChildIndex; // -1 = leaf
public short DataIndex; // index into NodeData; -1 = no data (plain composites/decorators)
}
Children are linked as a sibling list (FirstChild โ NextSibling chain), ordered left-to-right by canvas position. Sub-tree nodes are replaced in place by their sub-tree's root during flattening โ a NodeType.SubTree never appears in the compiled blob.
BtNodeData โ Per-Node Data Offsets
public struct BtNodeData
{
public short ConditionIndex; // โ Conditions (blackboard cond/modify, find/condition/transaction tables)
public short FloatIndex; // โ FloatData (params / timer values / spawn position)
public short HashIndex; // โ Hashes (node identity; +1 = prefab hash if HasPrefab; +2โฆ = ports)
public short ParallelIndex; // โ Parallels
public short StateIndex; // โ BtNodeState slot (timers, counters, named variable, visited mask)
public bool UseDeltaTime; // Blackboard Modify: scale value by ฮt
public bool HasPrefab; // shifts the port hash positions by one
public bool IsChanged => any index != -1;
}
A node only gets a NodeData entry when it carries data (IsChanged) โ plain Sequence/Selector/Inverter/Force* nodes are pure topology.
Hash Layout at HashIndex (per node kind)
| Node kind | Layout |
|---|---|
| custom action | [nodeHash] [prefabHash?] [inputPortHashโฆ] [outputPortHashโฆ] |
| Find | [nodeHash] [outEntityPortHash] [outPositionPortHash] |
| Condition | [nodeHash] [inEntityPortHash] |
| Change Entity | [nodeHash] [inEntityPortHash] |
| Create Entity | [prefabHash] [inPositionPortHash] [outEntityPortHash?] |
portHash = 0 โ unconnected โ BbIndices slot -1 (reads default / static fallback).
FloatData Layout (per node kind)
| Node kind | Layout |
|---|---|
| Wait | [seconds] |
| Delay | [frames] |
| Repeater / Retry | [count] |
| Cooldown | [seconds] |
| Parallel | (none โ uses Parallels table) |
| Blackboard Condition/Modify | *(none โ uses Conditions[ConditionIndex]) |
| Find | [findMode] [cellSizeยฒ] [distanceยฒ] |
| Create Entity | [x, y, z, useTransform(0/1), addParent(0/1)] |
| custom action | [param0, param1, โฆ] (booleans as 0/1) |
BtCondition โ Condition / Transaction Table
public struct BtCondition
{
public ushort Mask; // bit i = field i is active (operator != Skip)
public BlobArray<float> Values; // per-field value
public BlobArray<byte> Ops; // per-field operator
}
OpsareCompareOperator(Skip=0, Equal, NotEqual, Greater, Less) for Find/Condition checks, orModifyOperator(Skip=0, Set, Inc, Dec) for Change-Entity transactions โ the same struct serves both; the generated code decides the interpretation.- One
BtConditionentry per (component, purpose): Find/Condition nodes produce one entry per component (comparisons); Change-Entity produces one per component for buffer components (comparisons) and one for the transactions, plus one per non-buffer component (transactions only).ConditionIndexpoints at the first entry of the node's component list; the generated code indexes through them in order. - Field order within an entry follows the component's field declaration order (as reflected in the editor rows);
Maskuses the same indices. - Comparison of
Equal/NotEqualuses the 0.001 epsilon;Modifyclamps integer results to the field's type range (overflow โ the transaction fails, value untouched).
BtParallel
public struct BtParallel
{
public ParallelPolicy Policy; // RequireAllSuccess | RequireOneSuccess
public short ChildrenStartIndex; // โ ParallelChildren
public short ChildrenCount;
public short StateStartIndex; // โ the agent's BtParallelBranchState buffer
}
StateStartIndex is assigned during a post-flattening pass (CalculateParallelOffsets) โ Parallel branches anywhere in the tree (including inside sub-trees) get contiguous branch-state slots, which the baker sizes the agent's buffer to.
Pooled Tables & Sharing
FloatData,Hashes,Conditions,StateIndicesare pools: nodes reference positions in them; identical data across nodes is never duplicated in the blob.- State slots (
BtNodeState) are shared by hash โ the same named blackboard variable used in the parent tree and in a sub-tree occupies exactly one slot (GetOrCreateSharedState), and its default value initializes it at bake time. - Blackboard slots (
BtBlackboardEntry) are shared by port hash โ the same output port feeding N inputs maps to one slot.
Sizing Formulas (per agent, at bake time)
| Buffer | Size |
|---|---|
BtNodeState | NodeStateCount = unique shared state hashes (named variables) + one per Wait/Delay/Cooldown/Retry/Repeater/random-composite node + Parallel branch wait states |
BtBlackboardEntry | BlackboardCount = unique non-zero port hashes across the compiled tree |
BtParallelBranchState | sum of ChildrenCount over every Parallel in the tree |
BtActionState | 0 (grows at runtime, one entry per running custom/Find/Condition node instance) |
BtDebugState (editor) | Nodes.Length (resized on demand by the runner in Play Mode) |
๐งฌ ECS Component Reference
Every entity component and buffer in the package, grouped by where they live. All types are in SnivelerCode.AiBehavior.Runtime.Components.
On the Agent (baked by BtAgentAuthoring)
| Component | Kind | Content |
|---|---|---|
BtAgent | IComponentData | BlobAssetReference<BtBlob> Tree (the compiled tree โ read-only after baking), short CurrentNodeIndex, short LastNodeIndex, NodeStatus LastStatus, bool DebugReset (editor-only progress reset flag) |
DynamicBuffer<BtNodeState> | buffer, fixed size at bake | per-node working state (timers, counters, named variables, random masks) โ see Blob Layout |
DynamicBuffer<BtBlackboardEntry> | buffer, fixed size at bake | one 16-byte unmanaged slot per data-port channel (Tier 2 blackboard) |
DynamicBuffer<BtParallelBranchState> | buffer, fixed size at bake | per-Parallel-branch resume state |
DynamicBuffer<BtActionState> | buffer, grows at runtime | one entry per currently-running custom/Find/Condition node instance |
DynamicBuffer<BtDebugState> | buffer, editor only | per-node runtime status log driving the visual debugger; sized on demand |
<Bt{H:X}System.Tag> (per generated system) | tag, IEnableableComponent | per-action-type activation marker; enabled โ the agent has a running node of that action type |
BtActionBakeRequest | buffer (removed after bake) | compile-time list of (actionHash, hasPrefab, prefabHash) used by the generated baking system to install the Tags |
LocalTransform (+ dynamic transform) | component | baked automatically by BtAgentAuthoring (required for Find and any action with transform params) |
State Structs
BtNodeState โ the 4-byte working slot
public struct BtNodeState
{
public float Value; // alias: IntValue (int), UIntValue (uint)
}
One slot per (shared) state owner. Reinterpreted per node kind:
| Used by | Interpretation |
|---|---|
named blackboard variable / [BtBlackboard] port | the variable's value (float) |
Wait / Cooldown | remaining seconds (Wait) / ready-time in ms (Cooldown, UIntValue) |
Delay | target frame index (IntValue) |
Repeater / Retry | loop/attempt counter (IntValue) |
| Random Sequence/Selector | visited-children bitmask (IntValue) |
BtBlackboardEntry โ the 16-byte data slot
public struct BtBlackboardEntry
{
public BtBlackboardValue Value; // 16-byte union
}
BtBlackboardValue is an explicit-layout (16-byte) union: FloatValue, IntValue, BoolValue, DoubleValue, Float3Value, Int2Value, Float2Value. Written by output ports and [BtBlackboard]-less inputs read it; Entity ports store the handle in the first 8 bytes.
BtActionState
public struct BtActionState
{
public ulong ActionHash; // the generated system's ACTION_HASH
public short NodeIndex; // which node instance (unique per (tree position))
public NodeStatus Status; // Running โ written by the action system
}
BtParallelBranchState
public struct BtParallelBranchState
{
public short CurrentNodeIndex;
public short LastNodeIndex;
public NodeStatus Status;
}
BtDebugState (editor only)
public struct BtDebugState
{
public bool BlockReset;
public NodeStatus Status; // last status the debugger saw for this node index
}
The runner writes Status per visited node each frame (buffer auto-resizes to Nodes.Length); the editor's graph view colors nodes from it. BlockReset stops the "auto-restart on tree completion" in Play Mode (see Runtime Visual Debugging).
Queues & Singletons (world-level)
| Type | Kind | Role |
|---|---|---|
BtNodeRequestSingleton | singleton with DynamicBuffer<BtNodeRequest> | the runner โ dispatcher request queue (enable/disable action Tags, transaction routing) |
BtTransitionRequest | (struct) per-transaction-system queue element | Agent, Target, ActionHash, NodeIndex โ Change-Entity work items |
BtSpawnRequest | struct enqueued to BtSpawnSystem's world buffer | Agent, NodeIndex, Position |
BtSpawnEntityMarker | tag on freshly spawned entities (one frame) | Agent + BtBlackboardIndex โ routes the spawned entity into the output port |
BtGlobalPrefabRegistry | component on a scene registry entity | owns the DynamicBuffer<BtPrefabEntry> |
BtPrefabEntry | buffer element | Hash (prefab asset GUID hash) + Prefab (baked entity) |
BtRuntimeSettings | world singleton (baked by BtSettingsAuthoring) | MaxIterationsPerFrame, LogInfiniteLoopWarnings |
BtNodeRequest | struct | Agent, Target, ActionHash, NodeIndex, bool Active |
Prefab Pipeline Components
| System | Group | What it does |
|---|---|---|
BtPrefabBakingSystem | (bake) | collects BtPrefabBakeRequests from agents, bakes the referenced GameObjects once (dedup by hash) into a registry entity with BtGlobalPrefabRegistry + BtPrefabEntry buffer, in the agent's scene |
BtPrefabCacheSystem | Initialization | mirrors the registry buffer into a persistent NativeHashMap<ulong, Entity> (rebuilt only when the registry's contents change โ e.g. scene load) for O(1) hashโprefab lookup by BtSpawnSystem and [BtPrefab] action systems |
Enums (reference)
| Enum | Values |
|---|---|
NodeStatus | None, Success, Failure, Running, Aborted |
NodeType | None, Sequence, Selector, SelectorRandom, SequenceRandom, Waiting, Delay, Requested, Transaction, DecoratorCooldown, DecoratorInverter, DecoratorForceSuccess, DecoratorForceFailure, DecoratorRetry, DecoratorRepeater, Parallel, SpawnEntity, BlackboardModify, BlackboardCondition, SubTree |
ParallelPolicy | RequireAllSuccess, RequireOneSuccess |
CompareOperator | Skip, Equal, NotEqual, Greater, Less |
ModifyOperator | Skip, Set, Inc, Dec |
FindMode | First, Nearest, Random |
BtBlackboardType | Bool, Int, Float |
BaSystemType | None, Find, Condition, Dispatcher, Baker, Custom, Transaction, Spawn |
โ ๏ธ Pitfalls & Limitations
A consolidated list of the sharp edges, verified against the source. If you hit a "weird" behavior, check here first.
Trees & Nodes
- Children are ordered by canvas position, not creation order. The compiler sorts siblings by
Position.x(left โ right). Tidy your canvas; overlapping x-positions are ordered by the link list's remaining order. - At most 31 children per composite (random variants require โค 31 โ a hard compile-time assert; the visited bitmask is 32 bits).
- A tree with no root (or a root with no input) is dead.
BtAgentAuthoringbakes what it finds; the runner starts at index 0 of the flat table, which corresponds to the first node the editor exposes as root (topmost node without an input link). - Empty composites:
Sequence= Success,Selector= Failure. Not an error โ just vacuous. - Sub-trees are flattened at compile time โ a
SubTreenode type never appears in the blob. A sub-tree's root inherits the parent's parent; its blackboard variables become shared state slots (same variable โ same slot across the whole tree). - Circular sub-tree references are rejected at compile time with an error log, and the offending node is skipped (its children are disconnected) โ the tree still compiles.
- Node identity is by type+configuration hash, not by position. Renaming a custom struct's type or changing a Find node's Spatial Cell Size changes the node's hash โ a new generated system is produced (old Tag stays on baked agents until re-bake). Changing a
[BtParam]value does not change identity (params are data, inFloatData).
Custom Actions
- The query rule is silent. An agent missing any component/buffer in the
Processsignature simply doesn't run the action โ no log, just a hang (permanentRunning). Verify with the ECS debugger: if the Tag is enabled but the action system's query is empty for that agent, a component is missing. - Unattributed bare scalars get
default. AProcess(float x)with no[BtParam]/[BtInput]compiles but always receives0โ the generator has no mapping and passesdefaultsilently. [BtBlackboard]ports are strict: onlyfloat/int/uint; each must be connected in the graph (unconnected โ compiler error log at bake, slot index-1).Processis Burst-compiled. NoUnityEngine.Debug.Log(useBtLogger), no managed allocations, no coroutines, noSystemAPI. If you see[Burst]warnings about your struct, they are about yourProcessbody.- Abandonment has no callback. When a Parallel finishes early, running actions are disabled (Tag off) without notification. Don't rely on "my action always completes"; make side effects idempotent or explicitly handle restarts.
- One
[BtPrefab]per action, type must beEntity; unassigned prefab โ authoring-time error. The prefab is resolved at runtime from the scene's registry โ spawning from a sub-scene whose registry doesn't contain the prefab passesEntity.Null.
Runtime Timing
- Custom actions have โฅ 1 frame of activation latency (request โ Tag enable โ next execution) and their result is observed by the runner no earlier than the next runner pass. Design stateful actions around "ticked every frame while Running".
- Create-Entity output ports are one frame late (the spawned entity id arrives via the Initialization-group relay). The spawn itself completes the same frame (registry lookup is synchronous).
- Cooldown/elapsed time is real (unscaled) time โ
SystemAPI.Time.ElapsedTime;Waitis scaled (integratesฮt);Delayis frames. Mixing them in one design is a classic source of "why is this faster/slower than expected". MaxIterationsPerFrame(default 50) caps per-agent progress. A tree of all-immediate nodes (conditions, blackboard ops) that completes fully in one frame can trip the cap on deep trees โ you'll see an error log. Raise the setting inBtSettingsAuthoringrather than "fixing" the tree.- Determinism: sibling processing order is canvas order; Find/Random-composite randomness is seeded per
(entity, node, frame); the dispatcher and spawn systems sort their queues by entity index before parallel processing. Re-bake after any structural change to keep agents in sync.
Stateful Nodes
Retryaround custom/composite children can hang (see Decorators for the exact mechanism). Safe children:Wait/Delayand immediate-failing leaves.- All stateful nodes in the same Parallel branch share one wait-state slot (a deliberate optimization โ on a linear path, only one stateful node is active at a time; nested Parallel branches get their own slots). Consequence: you cannot run two independent timers in parallel within one branch via built-in nodes โ wrap the second one in a nested
Parallelif you need simultaneous timers. Repeaterwith0= infinite, and each iteration is a fresh run (state re-initialized). ARepeater โ Wait(1)that you interrupt (Parallel abort) loses the in-progress timer on restart.
Editor & Code Generation
- Two-stage generation โ respect the order. Stage 1 (editor) writes
SystemsNote.g.cs+ the generated asmdef when graphs/settings change; Stage 2 (Roslyn) reacts to[BtCustom]/[BtCondition]/[BaSystemNodes]types and the registry. Adding a new custom struct requires a Unity recompile (stage 2 runs then); adding a new node instance of an existing type does not (it's just data). [BtCondition]components are a closed set. Only types carrying the attribute appear in the Find/Condition/Change-Entity dropdowns. Adding/removing the attribute from a struct that is already used in a graph will break the generated systems on next compile (BA0003 until fixed) โ change such component types only with care.- The generated asmdef references your code. If your
[BtCustom]types move between assemblies, the generated asmdef may fail to resolve them (BA0003) โ the generatedAssembly-CSharp-style assembly references are derived from where the types live. - Auto-save is throttled (0.5 s) and flushes on play-mode entry. Closing Unity with unsaved graph changes in the throttle window can lose the last edit โ
Ctrl+S(Save button) is immediate. - Graph assets are the source of truth for identity (
AssetHash/TreeHashfrom the asset GUID). Duplicating a graph asset creates a new tree identity; agents referencing the old GUID keep the old tree until re-baked.
Performance
- Find cost is O(entities-with-components + (2r/cell)ยณ ร cell-occupancy). Keep
Max Distancetight and cell size near average entity spacing. The per-frameNativeParallelMultiHashMapin Find systems scales with world entity count for the configured components โ in worlds with tens of thousands of matching entities, consider reducing the component set (more specific components โ fewer candidates). - Baked prefabs are per-scene. Each scene that spawns gets its own registry (baked entities are scene-local). A prefab used across scenes must be baked in each.
- Agent count โ action cost: an agent only costs runner iterations for nodes that are active (Running) or being traversed this frame; idle agents (tree finished) reset to the root and run their first pass. If "finished = do nothing forever" is your intent, end the root in a
Waitwith a very large value or an infiniteRepeater โ Waitโ the tree's "completion" semantics are re-run from the root, not "stop".
Known Limitations Summary
| Limitation | Status |
|---|---|
Retry re-entry hang for custom/composite children | known; workaround documented |
| No cancellation callback for abandoned actions | by design; Tag-based stop only |
BtBlackboard (Tier 1) variables are float-only (4 bytes) | by design; Tier 2 ports cover wider types |
Find requires LocalToWorld on candidates and agent | by design (spatial index) |
No Aborted status propagation from user code | Aborted is internal (parallel-abort path only) |
| Editor-only debug state; no profiling overlays | out of scope for runtime |
๐ฌ Demo: Workers Sample
The package ships a complete Samples~/DemoWorkers sample โ a stress-test scene of GPU-animated workers (chopping/hammering at benches) driven entirely by Behavior Architect. It demonstrates the full pipeline at scale: custom actions with ports and params, buffer components, LOD switching from a tree, and dynamic agent spawning.
Getting the Sample
- Unity Package Manager โ Packages โ My Assets โ find Sniveler Code Ai Behavior Architect (see Installation if it isn't there yet).
- Click Samples โ Install "DemoWorkers" (or open the package โ Samples tab).
- Open the sample's
Workers.unityscene (aLanding.unityscene exists too). - Bake the sub-scene (the standard sub-scene baking workflow) and press Play.
The sample includes a GPU animation pipeline (
GpuAnimation/scripts) that is demo support code, not part of the behavior package โ it renders the worker characters. You can delete everything underGpuAnimation/and keep theAiBehavior/scripts if you only want to study the AI logic.
Scene & Prefab Layout
| Asset | Role |
|---|---|
Scene/Workers.unity | the main sub-scene: bench/workplace layout |
Prefabs/WorkPlace.prefab | a bench + chest + spawn slot group |
Prefabs/HammerWorker.prefab | a worker character with BtAgentAuthoring attached (graph assigned in the inspector) |
Scripts/AiBehavior/DemoAuthoring.cs | adds a DemoLodsBuffer (per-worker list of LOD entity ids) to the worker |
Scripts/AiBehavior/DemoChestAuthoring.cs | adds [BtCondition] DemoChestTag to the chest โ making it a query target for Find/Condition nodes |
Scripts/AiBehavior/DemoBenchAuthoring.cs | workplace tagging/components |
Scripts/AiBehavior/DemoSpawnerAuthoring.cs / DemoSpawnerSystem.cs | runtime batch spawner: instantiates โN work-places + workers per frame (grid layout, 1.25 ร 4.0 units spacing) until Total is reached, then disables itself โ this is how the stress test scales to thousands of agents |
Scripts/AiBehavior/DemoToolSystem.cs / DemoBenchAuthoring | bench-side state (tool progress) that the workers' trees read/write |
The Custom Actions (study these)
DemoMoveAction โ the reference action
[BtCustom("Demo/Move")]
public partial struct DemoMoveAction
{
[BtDeltaTime] public float DeltaTime;
private NodeStatus Process([BtInput] float3 target,
[BtParam] float speed,
ref LocalTransform transform,
DynamicBuffer<AnimatorParameterData> parameters)
{
// moves toward `target` at `speed` units/s, triggers a "walk" animation
// parameter while moving, and returns Running until close enough
}
}
It shows the full toolbox in one node: an input port (target from a Find/Blackboard), a param (speed, tunable per instance), a ref component (the agent's own transform), a buffer (GPU-animation parameters), and [BtDeltaTime].
DemoAnimatorAction โ enum params & buffers
[BtCustom("Demo/Animator")]
public partial struct DemoAnimatorAction
{
private NodeStatus Process(DynamicBuffer<AnimatorParameterData> parameters,
[BtParam] AnimatorTrigger trigger, // enum param โ dropdown
[BtParam] float value)
{ /* sets an animation parameter */ }
}
Demonstrates enum [BtParam] (the inspector renders a dropdown; the blob stores the int) and buffer access.
DemoLodsAction โ lookups + buffer params
[BtCustom("DemoLods")]
public partial struct DemoLodsAction
{
[NativeDisableParallelForRestriction]
public ComponentLookup<LocalTransform> Transforms;
private NodeStatus Process([BtParam] int lodIndex,
[BtParam] float enable,
DynamicBuffer<DemoLodsBuffer> lodsBuffer)
{
Transforms[lodsBuffer[lodIndex].Value] = LocalTransform.FromScale(enable);
return NodeStatus.Success;
}
}
The clearest demonstration of random-access lookup usage: the agent's own buffer holds the ids of its LOD mesh entities, and a lookup (exempt from the query) rescales the selected LOD's transform. Note the [BtParam] float enable โ 0 hides a LOD, 1 shows it. (The [NativeDisableParallelForRestriction] is needed because the lookup write targets a different entity than the job's โ standard ECS practice for cross-entity lookups inside IJobChunk.)
What the Worker Trees Look Like
The included worker graph combines, in a single tree:
- a Find (nearest entity with
DemoChestTagwithin radius) โ the chest drives work selection, - Condition gates on the agent's own state components,
Demo/Moveto walk to the bench,Demo/Animatorto play the work animation,DemoLodsto toggle LOD meshes based on tree context,- a Repeater/Sequence loop around the whole work cycle.
Open the graph asset assigned to HammerWorker.prefab's BtAgentAuthoring and use the Visual Debugger during Play Mode to watch the flow move.
Running the Stress Test
- Add a
DemoSpawnerAuthoring(or use the scene's existing one) with your target Total (e.g. 1000). - Bake, Play. The spawner adds a grid of workers every frame until the total is met โ you can watch agent count, CPU, and the debugger's per-frame cost scale.
- Use
BtSettingsAuthoring'sMaxIterationsPerFrame/logging to see the iteration guard in action on pathological trees.
๐ก This sample is intentionally a stress scene โ hundreds/thousands of agents with non-trivial trees. If you are learning the package, start from the Quick Start with a single hand-rolled agent, then scale up with this sample's patterns.
๐งช Testing
The package ships a test suite covering the compiler, editor utilities, code generation, and key runtime invariants. Understanding what's tested helps you reason about what's guaranteed versus what's your responsibility.
Test Layout
| Assembly | Files | What they cover |
|---|---|---|
Tests/Editor (SnivelerCode.AiBehavior.Tests.Editor) | BtCompilerIntegrationTests.cs | BtCompiler.Compile on real GraphAssets: node flattening, sibling ordering, sub-tree inlining, shared state slots, blackboard slot dedup, condition/float/hash pooling, parallel branch offsets, NodeStateCount/BlackboardCount sizing |
BtCodeGeneratorTests.cs | Stage-1 generation: SystemsNote.g.cs content, registry JSON, asmdef emission, content-hash gating (no rewrite when unchanged) | |
BtGraphUtilsTests.cs | Graph editing utilities (link/port helpers, root detection) | |
BtSettingsTests.cs | BtSettings defaults, Instance asset creation, authoring bake values | |
Tests/Runtime (SnivelerCode.AiBehavior.Tests) | BtRuntimeLogicTests.cs | runtime logic exercised in-world: runner transitions, decorator semantics, blackboard condition/modify operators (including the 0.001 epsilon), wait/delay/completion paths |
BtParallelDeactivationTests.cs | the Parallel-abort path: a running custom action under an abandoned branch receives a deactivation request (Tag disabled) โ the guarantee described in Composites | |
BtUtilsTests.cs | BtUtils helpers (hashing, prefab resolution) |
Running the Tests
- Unity โ Window โ General โ Package Manager โ Testing (or install Packages โ Testing if absent).
- Window โ General โ Testing โ Run All Tests โ both editor and runtime groups run. Runtime tests create their own world/entities and exercise real compiled blobs, so they are the authoritative source on runtime semantics.
- For CI-style runs:
unity -batchmode -runTests -testFilter "SnivelerCode.AiBehavior.Tests"(adjust to your Unity install path).
What the Tests Guarantee (and what they don't)
Guaranteed:
- the compiler's structural invariants (flattening, sharing, sizing) โ if a tree shape compiles differently than the tests expect, a test fails;
- the blackboard operator semantics (
Set/Inc/Dec, comparisons with epsilon, overflow clamping); - the Parallel-abort deactivation contract;
- decorator completion rules for the tested paths.
Your responsibility (not covered by the package tests):
- your custom actions โ the generated system is compiled from your code; write tests for your own
Processlogic (they run as normal C# in editor test contexts, or in a runtime test world); - tree design correctness โ the framework executes your tree faithfully; whether the tree does what you intended is yours to verify (the Visual Debugger is the fastest tool for this);
- integration with your world (transform usage, scene layout, prefab registry presence per scene).
Recommended Regression Checks When Upgrading
- Run the package's full test suite after upgrading the package (behavior changes land with changelog entries; tests catch regressions).
- Re-bake all agent scenes (
BtAgentAuthoringbakes at bake time โ a package upgrade changes generated code, so a re-bake picks up new system behavior). - If you changed any
[BtCondition]components, Find/Condition/Change-Entity node configs, or custom action signatures: verify the generated assembly still compiles (BA0003 warnings surface there) and spot-check one agent per graph in Play Mode.