๐Ÿ‘‹ 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-oriented MonoBehaviour workflows. 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?

โœจ Core Features at a Glance

๐Ÿ“ฆ Package Facts

PropertyValue
Package namesniveler-code.dev.ai-behavior-architect
Display nameAI Behavior Architect
Current version1.1.x
Minimum Unity2022.3 (0f1)
Required dependenciescom.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 dependenciesURP / HDRP 14.0.9 (required by the Demo Workers sample only)
Render pipelineCore framework is 100% pipeline-agnostic (Built-in, URP, HDRP)

๐Ÿ“š How This Documentation is Organized


๐Ÿง  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

#StageWhere it runsReadsProduces
1Editor compileEditor โ€” BtCodeGenerator, triggered by the Compile button (or auto on save)every GraphAsset in the projectSystemsNote.g.cs (the [BaSystemNodes] registry) + SnivelerCode.AiBehavior.Generated.asmdef, written into your Generated Directory
2Roslyn code generationthe C# compiler โ€” AiBehaviorAnalyzer (incremental IIncrementalGenerator)the [BtCustom] structs, [BtCondition] components and the generated [BaSystemNodes] class in your compilationone Burst ISystem + IJobChunk per unique node configuration (custom actions, Find, Condition, Transaction), plus the shared BtBakingSystem and BtDispatcherSystem
3Sub-scene bakesub-scene baking โ€” BtAgentAuthoring.Baker, once per agent GameObjectthe compiled registry + the agent's assigned GraphAsseta 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)
4Per-frame runtimeevery simulation framethe blob + the agent's state buffersbehavior: 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:

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 attributeTargetGenerated output
[BtCustom("Name")]your partial structBt{HASH:X}System : ISystemplus the rest of your partial struct turned into a [BurstCompile] IJobChunk. Lives in your namespace.
[BtCondition]component structspartial 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 classOne 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:

๐Ÿ’ก 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:

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. No GameObject walks, 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:

BufferElement typePurpose
BtNodeState4-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.
BtBlackboardEntry16-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):

  1. BtDebugInitSystem (editor only) โ€” ensures every agent has a BtDebugState buffer.
  2. BtRunnerSystem โ€” Burst IJobEntity scheduled 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.
  3. 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.
  4. Generated action systems (one per unique Find / Condition / custom action) โ€” Burst IJobChunk jobs over the agents whose Tag is enabled; they call your Process method and write the resulting NodeStatus back into BtActionState.
  5. BtSpawnSystem โ€” drains spawn requests from Create-Entity nodes and instantiates baked prefabs through an EndSimulationEntityCommandBuffer.
  6. Next frame's Initialization group: BtPrefabCacheSystem (keeps an O(1) prefab-hash โ†’ entity map) and BtSpawnBlackboardSystem (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

RequirementMinimum VersionNotes
Unity2022.3 (2022.3.0f1)Any later 2022.3 LTS patch or 6000 series release works
Entities (com.unity.entities)1.4.5Core ECS/DOTS package
Entities Graphics (com.unity.entities.graphics)1.4.18Required by the package manifest; only needed if you render DOTS entities
Burst Compiler (com.unity.burst)1.8.27Compiles the runner and all generated systems
Mathematics (com.unity.mathematics)1.3.2float3, quaternion, Random, โ€ฆ
Collections (com.unity.collections)2.6.5NativeQueue, NativeParallelMultiHashMap, โ€ฆ
URP / HDRP (optional)14.0.9Only 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 classic MonoBehaviour-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)

  1. Place the sniveler-code.dev.ai-behavior-architect package folder (the one containing the package's package.json) somewhere on disk โ€” outside your project is the common layout, inside works too.
  2. In Unity: Window โ†’ Package Manager (with the Project package view selected) โ†’ click the + button โ†’ Add package from diskโ€ฆ
  3. Select the package folder.
  4. 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

  1. Obtain the current AI Behavior Architect.unitypackage from the publisher.
  2. In Unity: Assets โ†’ Import Package โ†’ Custom Packageโ€ฆ and select the file.
  3. Unity imports the package into your project and resolves the DOTS dependencies for you.

Samples (both options):

โœ… Post-Installation Checklist

  1. 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.
  2. Open Project Settings (Edit โ†’ Project Settings โ†’ AI Behavior Architect) and verify the Generated Directory โ€” see Project Setup.
  3. (Optional) Demo Workers: the sample requires URP. After importing it, run AI Behavior Architect โ†’ Demo Workers โ†’ Setup URP Pipeline (see Demo Workers Sample).
  4. 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 .asmdef picks 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

  1. Open Edit โ†’ Project Settings.

  2. Select the AI Behavior Architect tab in the left-hand menu (the settings provider registers it under Project/AI Behavior Architect).

  3. Generated Directory โ€” the folder where generated sources and the generated .asmdef are written. Default: Assets/SnivelerCode/AiBehavior/Generated. Use the Browse button to pick any folder under Assets/.

  4. 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:

  1. 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.
  2. Scans every GraphAsset in 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" }
            }
        };
    }
}

SnivelerCode.AiBehavior.Generated.asmdef

An assembly definition that references:

๐Ÿ’ก 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 makeCode regenerated?Re-bake needed?
Move/drag nodes, change graph view transformNoYes (Play Mode)
Change a node's parameter (Wait time, Find distance, blackboard value)NoYes (Play Mode)
Add/remove a component in Find/Condition/Change-EntityYes (new hash โ†’ new system)Yes
Change a Find node's Spatial Cell SizeYes (cell size is part of the hash)Yes
Change a Find node's Max Distance or Find ModeNo (runtime data from blob)Yes
Add a new [BtCustom] action type to your codeNot by the editor โ€” the Roslyn generator picks it up on the next compile of your assemblyYes
Change a [BtCustom] Process signatureRoslyn generator on next compileYes
Add a new GraphAsset that reuses existing configsNoYes

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

  1. In the Project window, right-click anywhere.
  2. Go to Create โ†’ Entities โ†’ Sniveler Code โ†’ AI Graph and name it, e.g. MyFirstAgent.
  3. Open the editor: Window โ†’ Sniveler Code โ†’ AI Behavior Architect.
  4. Drag the MyFirstAgent asset into the Active Tree slot in the top toolbar.

Step 2 โ€” Add Logic Nodes

  1. Right-click the empty grid (or press Spacebar) to open the Node Search Window.
  2. Search for Composite Sequence (under Composites) and click it to place a Sequence node.
  3. Search for Action Wait (under Actions) and place a Wait node to its right.
  4. Drag from the bottom (Output) flow port of the Sequence to the top (Input) flow port of the Wait.
  5. Select the Wait node โ€” 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

  1. In the left panel, click Compile.
  2. Watch the Console: you should see [BT Architect] Graph compiled successfully. Generating DOTS systems... followed by a normal C# compile of the generated assembly.
  3. Peek into your Generated Directory (Assets/SnivelerCode/AiBehavior/Generated): SystemsNote.g.cs now exists. (A bare Sequence + Wait tree needs no generated action systems โ€” those only appear when you use Find / Condition / Change-Entity / custom actions.)

Step 4 โ€” Set Up the Agent Entity

  1. 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.
  2. Create a new empty GameObject in that sub-scene, e.g. AI Agent.
  3. Add the BtAgentAuthoring component and drag your MyFirstAgent graph into its Tree field.
  4. (Optional) Add BtSettingsAuthoring to 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.

โš ๏ธ 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 see BtCompiler: 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

  1. Make sure the sub-scene is closed (not open in a Scene view) so it bakes on Play.
  2. Press Play.
  3. Open Window โ†’ General โ†’ Entity Hierarchy (provided by the Entities package) and select your AI Agent entity.
  4. With the Behavior Editor still open, it automatically switches to the graph running on the selected entity โ€” and you'll see the Sequence and Wait nodes 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


๐ŸŽจ 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:

ZoneLocationContents
Top Toolbaracross the topActive 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 Panelleft columntwo stacked tabs โ€” Node Settings (inspector for the selected node) and Variables (the graph's blackboard variables) โ€” with the Compile button below them
Graph Canvasright, main areathe 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

๐ŸŽ› 2. The Settings Panel (Left)

A vertical panel with two stacked tabs plus the compile button:

๐Ÿ—บ 3. The Graph Canvas (Right)

Ports: Flow vs. Data

Every node exposes two port families:

Port familyVisual positionTypeCapacityMeaning
Flow (logic) portstop / bottom of the nodeFlowInput: single ยท Output: multi (composites) / single (decorators, leaves)Execution order. The bottom port is always the child connection point.
Data portsleft / right of the nodethe payload's CLR type (or a marker type)single, mostly multi for outputsPass 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:

  1. saves the dirty graph asset,
  2. recompiles if Auto Compile On Save is on,
  3. 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

๐Ÿšจ 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

  1. Create a new AI Graph asset (Create โ†’ Entities โ†’ Sniveler Code โ†’ AI Graph), e.g. Sub_MeleeAttack.
  2. Open your main tree in the Behavior Editor.
  3. Add a Composites โ†’ Composite Sub-Tree node.
  4. Select it and assign the Sub_MeleeAttack asset 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

โš ๏ธ 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:

๐Ÿ’ก 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

  1. Enter Play Mode (the editor auto-switches to read-only and locks the canvas).
  2. Open the Entity Hierarchy window (Window โ†’ General โ†’ Entity Hierarchy, provided by the Entities package).
  3. Select any entity that carries a BtAgent component.
  4. If the Behavior Editor is open, it snap-loads the graph asset that the selected entity is running (resolved by matching the blob's TreeHash against 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 colorMeaning
๐ŸŸก YellowThe node is currently Running (it will be re-ticked next frame).
๐ŸŸข GreenThe node returned Success this frame. The highlight fades after ~0.5 s.
๐Ÿ”ด RedThe node returned Failure this frame. The highlight fades after ~0.5 s.
โฌœ GrayIdle โ€” 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.

๐Ÿ’ก You can opt into managed logging in the editor for deeper diagnostics: define SNC_DEBUG_INFO (info) and/or SNC_DEBUG_WARNINGS in your assembly's player settings or a scripting define. BtLogger.LogManaged and BurstLogBuilder.LogWarning only emit under those defines.

๐Ÿ› What to Look For (Common Debug Patterns)


๐Ÿง  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
BufferDynamicBuffer<BtNodeState>DynamicBuffer<BtBlackboardEntry>
Slot size4 bytes โ€” float union (float / int / bool / uint)16 bytes โ€” unmanaged union (any unmanaged type โ‰ค 16 bytes: float, int, double, float2, int2, float3, Entity, โ€ฆ)
How createdby designers in the editor's Variables tab (name + type + default value)automatically, one slot per unique connected horizontal port
Identitythe variable's hash โ€” FNV-1a of a GUID, assigned when the variable is createdthe port's hash โ€” FNV-1a of a GUID, stored in the node data
Used byBlackboard Condition / Blackboard Modify nodes; [BtBlackboard] parameters of custom actionsFind / 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:

At bake time the compiler registers every variable (including sub-tree variables) into a shared state table keyed by hash:

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

ConsumerHow it's wired
Blackboard Condition nodethe inspector's Variable dropdown picks a variable โ†’ the node reads its slot
Blackboard Modify nodesame; 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/uint only). [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:

๐Ÿ’ก 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"):

Lifetime & Reset

Performance Note

In object-oriented frameworks, blackboards are typically Dictionary<string, object> โ€” allocation-heavy and unusable in Burst. Here:


๐ŸŽ› 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:

FieldMeaning
Variabledropdown of the graph's named variables (by name; identity is the hash)
OperatorSkip, Equal, NotEqual, Greater, Less
Valuethe static value to compare against (float field)
Enable Outputwhen 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):

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:

FieldMeaning
Variablethe variable to modify
OperatorSkip, Set, Inc (add), Dec (subtract)
Valuethe static value
Use DeltaTimewhen enabled, Value is multiplied by DeltaTime before the operation (per-frame accumulation โ€” see below)
Enable Outputsame output-port behavior as Condition

Runtime semantics (exact):

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.

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.

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:

โš ๏ธ 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):

PolicyCompletes whenโ€ฆResult
Require All Success (default)any child returns Failure โ†’ abortFailure
all children finish (no failures)Success
Require One Successany child returns Success โ†’ abortSuccess
all children finish with no successFailure

Abort behavior (exact): when the Parallel completes, every branch still Running is abandoned:

  1. each abandoned branch's running custom/Find/Condition action is removed from BtActionState,
  2. 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 BtParallelDeactivationTests verifies).

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:


๐ŸŽ€ 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.

Use case: Chop Tree 5 times. The value 0 + a Blackboard 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.

โš ๏ธ Known limitation โ€” custom/composite children can hang (verified against BtRunnerSystem). On the retry re-entry the child is resumed in Running state, and the resume point stays on the child. Each node type handles a Running re-entry differently:

  • Wait / Delay โ€” correct: their handlers treat Running as "continue my timer", so Retry โ†’ [Wait, then attempt] works as expected.
  • Custom actions (Requested/Transaction) โ€” hang: the child's failure already removed its BtActionState entry, and the Running re-entry path in ProcessCustomAction only observes an existing state โ€” with none present it does not re-enqueue the request. The agent then sleeps forever on that node (permanent Running in the debugger).
  • Composites (Sequence/Selector/random variants) โ€” hang the same way: they have no Running re-entry case at all.

Workarounds for retry semantics around custom logic:

  • make the custom action retry internally โ€” it re-runs Process every frame while Running, 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 a Wait between attempts works out of the box).

โณ Cooldown

Decorators/Decorator Cooldown

Gates its child with a real-time cooldown measured against SystemAPI.Time.ElapsedTime.

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:

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:

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

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

Wait vs. Delay โ€” which to use?

WaitDelay
Unitseconds (float)frames (int)
Time scalingscales with DeltaTime (slow-mo stretches it)frame-locked โ€” always exactly N frames regardless of FPS
Precisionsub-frame (completes mid-frame)whole frames
Use whengame-time durations (cooldowns, animation sync)frame-exact timing (deterministic step patterns, per-N-frames behavior)

โš ๏ธ Under a fixed-timestep simulation both behave as described. Delay is 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


๐Ÿ”Ž 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/Modify extension methods for it โ€” the field-level condition/transaction evaluators the generated systems call. Supported field types are bool, 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:

FieldMeaning
Find MethodFirst (fastest), Nearest (closest match), Random (uniform random match)
Max Distancesearch radius (world units). Distance check is a true sphere around the agent.
Spatial Cell Sizeedge length of the hash cells (also part of the node's hash โ€” changing it generates a new system)
Complexityread-only estimator: min(100, round(2 ยท (Distance/Cell)ยณ)) โ€” the approximate number of cells scanned
Components Setupone or more [BtCondition] components, each with per-field conditions (operator dropdown per field: Skip/Equal/NotEqual/Greater/Less + value)

Data ports (outputs):

PortTypeContent
EntityEntitythe found entity (written to the port's blackboard slot)
float3float3the 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):

  1. Collect job โ€” one IJobChunk over all entities that have all required components and a LocalToWorld transform: each is inserted into a NativeParallelMultiHashMap<int3, Result> keyed by floor(position / CellSize). Result carries the component values, the entity, and its position.
  2. 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 distSq to the agent and rejects beyond rยฒ,
    • 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 (goto out of the cell loops); Nearest โ†’ keep the smallest distSq; Random โ†’ reservoir-style: replace the current pick with probability 1/candidates (uniform over all matches),
    • on a match: writes Entity and float3 into the agent's blackboard slots and sets the action Success; otherwise Failure.

Tuning tips:

๐Ÿงพ 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-check Condition: MyStatus == Dead as 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:

FieldMeaning
Entity input porttarget; 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):

Use case: damage application (Health.Dec 10 on 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 an EntityCommandBuffer (see Entity Command Buffers).

๐Ÿฃ Query Create Entity (spawn)

Queries/Query Create Entity โ€” spawns a baked prefab at runtime.

Inspector:

FieldMeaning
Entitythe 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 Transformwhen 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 Outputgrows 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

  1. partial struct โ€” the generator declares the other half of the struct (as an IJobChunk) in your namespace. Forgetting partial is the #1 cause of confusion.
  2. [BtCustom("โ€ฆ")] on the struct โ€” registers the type with the editor's search window and with the Roslyn generator.
  3. A private NodeStatus Process(...) method โ€” any access level works as long as it's named Process; it must return NodeStatus. 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:

  1. Open the Behavior Editor โ†’ right-click / Spacebar โ†’ search window.
  2. Pick Actions โ†’ Action Custom โ€” the node's inspector shows a dropdown of every [BtCustom] type in the project (displayed as Namespace/StructName), plus one field per [BtParam] parameter.
  3. 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:

๐Ÿ’ก 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's BtActionState buffer, 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):

ReturnMeaning
NodeStatus.Runningkeep ticking โ€” Process is called again next frame (this is how you build stateful actions: timers, movement, waiting)
NodeStatus.Successcompleted successfully โ€” the node reports Success to its parent
NodeStatus.Failurefailed โ€” 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:

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 Process must 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: Process is never called, the BtActionState entry stays Running forever, the Tag stays enabled, and the agent's tree hangs on that node (watch for the permanent yellow border in the debugger).

Design guidance:

State, Identity and the Tag

Performance Characteristics


๐Ÿท 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) { }

[BtInput] โ€” dynamic value from a data-port channel

private NodeStatus Process([BtInput] float3 targetPosition) { }

[BtOutput] โ€” dynamic value to a data-port channel

private NodeStatus Process([BtOutput] ref float3 currentPosition) { }

[BtBlackboard] โ€” named blackboard variable (4-byte slot)

private NodeStatus Process([BtBlackboard] float health) { }
private NodeStatus Process([BtBlackboard] ref float health, [BtBlackboard] int state) { }

[BtEntityIndex] โ€” the agent's deterministic sort key

private NodeStatus Process([BtEntityIndex] int index, in Entity self) { }

[BtPrefab] โ€” prefab resolved from the global registry

private NodeStatus Process([BtPrefab] Entity projectile) { }

Bare (unattributed) Parameters

Parameter shapeInterpretation
Entity e (no attribute)The agent's own entity (entities[i])
in T comp / ref T comp where T : IComponentDataQuery component โ€” added to the system query; passed by value / by reference (see ECS Components in Custom Nodes)
DynamicBuffer<T> buffer where T : IBufferElementDataQuery buffer โ€” added to the query; element access via buffer[i]โ€ฆ (pass by value; write elements back explicitly)
A type matching a [BtSingleton] fieldthe 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;

[BtCommandBuffer(typeof(SomeSystem))]

[BtCommandBuffer(typeof(EndSimulationEntityCommandBufferSystem))]
public EntityCommandBuffer.ParallelWriter CommandBuffer;

[BtSingleton(typeof(MarkerComponent))]

[BtSingleton(typeof(WorldConfig))]
public WorldConfig Config;

ComponentLookup<T> / BufferLookup<T> fields

public ComponentLookup<LocalTransform> Transforms;          // read/write
[ReadOnly] public BufferLookup<ScoreBuffer> Scores;         // read-only

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 ] โ€ฆ

Error Codes You May See

CodeMeaning
BA0001Process doesn't return NodeStatus (or is missing)
BA0002generation failure โ€” invalid type parse, no valid components for a registered system, or [BtBlackboard]/[BtPrefab] with an unsupported type
BA0003warning: 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;
}

Writing Data โ€” ref

private NodeStatus Process(ref LocalTransform transform, [BtParam] float speed)
{
    transform.Position.y += speed * DeltaTime;
    return NodeStatus.Running;
}

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;
}

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;
    }
}

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

MechanismWhich componentsQuery membershipTypical use
in / ref parameterany IComponentData (incl. engine types like LocalTransform)required on the agentthe agent's own core data
DynamicBuffer<T> parameterany IBufferElementDatarequired on the agentthe agent's own buffers
ComponentLookup<T> / BufferLookup<T> fieldanythingnot requiredtargets, optional components
Find / Condition / Change-Entity nodesonly [BtCondition]-tagged typesn/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

  1. [BtCommandBuffer(typeof(<SystemGroup>))] on an EntityCommandBuffer.ParallelWriter field โ€” tells the generator to create a command buffer from that system group's singleton each frame and hand you its ParallelWriter:
[BtCommandBuffer(typeof(EndSimulationEntityCommandBufferSystem))]
public EntityCommandBuffer.ParallelWriter CommandBuffer;

The group type you pass decides when the commands replay:

GroupReplaysUse for
EndSimulationEntityCommandBufferSystemend of the simulation stepthe default choice โ€” most structural changes
BeginSimulationEntityCommandBufferSystemstart of the simulation stepchanges that must be visible to this frame's systems
PostPhysicsEntityCommandBufferSystemafter physicsphysics-related structural changes
any other โ€ฆEntityCommandBufferSystemat that group's replay pointspecialized pipelines
  1. [BtEntityIndex] on an int parameter โ€” 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

OperationIn a custom action?How
Modify existing component dataโœ… freelyref 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:

The Evaluator State Machine

BtRunnerSystem schedules BtRunnerJob : IJobEntity (Burst). Per agent:

  1. Resume point: the agent's BtAgent.CurrentNodeIndex (persisted component). -1 means "tree finished" โ†’ reset to 0 (re-run the root) and set DebugReset for the editor.
  2. Tick loop: a while loop steps the state machine; each iteration dispatches on NodeType (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).
  3. Custom actions (Requested / Transaction): the runner never runs them. It records a BtActionState{ActionHash, NodeIndex, Running} and enqueues a BtNodeRequest; on re-entry it reads the status the generated system wrote. Terminal statuses remove the state entry (and a Success on a node that has a flow child descends into it).
  4. Parallel: each branch is an independent mini-state-machine stored in the BtParallelBranchState buffer (its own CurrentNodeIndex/LastNodeIndex/Status). On completion, abandoned branches get their running actions deactivated (see Composites).
  5. 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:

FieldDefaultMeaning
MaxIterationsPerFrame50per-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.
LogInfiniteLoopWarningstruewhen 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)


๐Ÿ—ƒ 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 kindLayout
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 kindLayout
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
}

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

Sizing Formulas (per agent, at bake time)

BufferSize
BtNodeStateNodeStateCount = unique shared state hashes (named variables) + one per Wait/Delay/Cooldown/Retry/Repeater/random-composite node + Parallel branch wait states
BtBlackboardEntryBlackboardCount = unique non-zero port hashes across the compiled tree
BtParallelBranchStatesum of ChildrenCount over every Parallel in the tree
BtActionState0 (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)

ComponentKindContent
BtAgentIComponentDataBlobAssetReference<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 bakeper-node working state (timers, counters, named variables, random masks) โ€” see Blob Layout
DynamicBuffer<BtBlackboardEntry>buffer, fixed size at bakeone 16-byte unmanaged slot per data-port channel (Tier 2 blackboard)
DynamicBuffer<BtParallelBranchState>buffer, fixed size at bakeper-Parallel-branch resume state
DynamicBuffer<BtActionState>buffer, grows at runtimeone entry per currently-running custom/Find/Condition node instance
DynamicBuffer<BtDebugState>buffer, editor onlyper-node runtime status log driving the visual debugger; sized on demand
<Bt{H:X}System.Tag> (per generated system)tag, IEnableableComponentper-action-type activation marker; enabled โ‡” the agent has a running node of that action type
BtActionBakeRequestbuffer (removed after bake)compile-time list of (actionHash, hasPrefab, prefabHash) used by the generated baking system to install the Tags
LocalTransform (+ dynamic transform)componentbaked 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 byInterpretation
named blackboard variable / [BtBlackboard] portthe variable's value (float)
Wait / Cooldownremaining seconds (Wait) / ready-time in ms (Cooldown, UIntValue)
Delaytarget frame index (IntValue)
Repeater / Retryloop/attempt counter (IntValue)
Random Sequence/Selectorvisited-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)

TypeKindRole
BtNodeRequestSingletonsingleton with DynamicBuffer<BtNodeRequest>the runner โ†’ dispatcher request queue (enable/disable action Tags, transaction routing)
BtTransitionRequest(struct) per-transaction-system queue elementAgent, Target, ActionHash, NodeIndex โ€” Change-Entity work items
BtSpawnRequeststruct enqueued to BtSpawnSystem's world bufferAgent, NodeIndex, Position
BtSpawnEntityMarkertag on freshly spawned entities (one frame)Agent + BtBlackboardIndex โ€” routes the spawned entity into the output port
BtGlobalPrefabRegistrycomponent on a scene registry entityowns the DynamicBuffer<BtPrefabEntry>
BtPrefabEntrybuffer elementHash (prefab asset GUID hash) + Prefab (baked entity)
BtRuntimeSettingsworld singleton (baked by BtSettingsAuthoring)MaxIterationsPerFrame, LogInfiniteLoopWarnings
BtNodeRequeststructAgent, Target, ActionHash, NodeIndex, bool Active

Prefab Pipeline Components

SystemGroupWhat 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
BtPrefabCacheSystemInitializationmirrors 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)

EnumValues
NodeStatusNone, Success, Failure, Running, Aborted
NodeTypeNone, Sequence, Selector, SelectorRandom, SequenceRandom, Waiting, Delay, Requested, Transaction, DecoratorCooldown, DecoratorInverter, DecoratorForceSuccess, DecoratorForceFailure, DecoratorRetry, DecoratorRepeater, Parallel, SpawnEntity, BlackboardModify, BlackboardCondition, SubTree
ParallelPolicyRequireAllSuccess, RequireOneSuccess
CompareOperatorSkip, Equal, NotEqual, Greater, Less
ModifyOperatorSkip, Set, Inc, Dec
FindModeFirst, Nearest, Random
BtBlackboardTypeBool, Int, Float
BaSystemTypeNone, 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

  1. 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.
  2. At most 31 children per composite (random variants require โ‰ค 31 โ€” a hard compile-time assert; the visited bitmask is 32 bits).
  3. A tree with no root (or a root with no input) is dead.BtAgentAuthoring bakes 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).
  4. Empty composites:Sequence = Success, Selector = Failure. Not an error โ€” just vacuous.
  5. Sub-trees are flattened at compile time โ€” a SubTree node 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).
  6. 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.
  7. 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, in FloatData).

Custom Actions

  1. The query rule is silent. An agent missing any component/buffer in the Process signature simply doesn't run the action โ€” no log, just a hang (permanent Running). 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.
  2. Unattributed bare scalars get default. A Process(float x) with no [BtParam]/[BtInput] compiles but always receives 0 โ€” the generator has no mapping and passes default silently.
  3. [BtBlackboard] ports are strict: only float/int/uint; each must be connected in the graph (unconnected โ‡’ compiler error log at bake, slot index -1).
  4. Process is Burst-compiled. No UnityEngine.Debug.Log (use BtLogger), no managed allocations, no coroutines, no SystemAPI. If you see [Burst] warnings about your struct, they are about yourProcess body.
  5. 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.
  6. One [BtPrefab] per action, type must be Entity; 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 passes Entity.Null.

Runtime Timing

  1. 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".
  2. 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).
  3. Cooldown/elapsed time is real (unscaled) time โ€” SystemAPI.Time.ElapsedTime; Wait is scaled (integrates ฮ”t); Delay is frames. Mixing them in one design is a classic source of "why is this faster/slower than expected".
  4. 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 in BtSettingsAuthoring rather than "fixing" the tree.
  5. 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

  1. Retry around custom/composite children can hang (see Decorators for the exact mechanism). Safe children: Wait/Delay and immediate-failing leaves.
  2. 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 Parallel if you need simultaneous timers.
  3. Repeater with 0 = infinite, and each iteration is a fresh run (state re-initialized). A Repeater โ†’ Wait(1) that you interrupt (Parallel abort) loses the in-progress timer on restart.

Editor & Code Generation

  1. 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).
  2. [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.
  3. The generated asmdef references your code. If your [BtCustom] types move between assemblies, the generated asmdef may fail to resolve them (BA0003) โ€” the generated Assembly-CSharp-style assembly references are derived from where the types live.
  4. 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.
  5. Graph assets are the source of truth for identity (AssetHash/TreeHash from 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

  1. Find cost is O(entities-with-components + (2r/cell)ยณ ร— cell-occupancy). Keep Max Distance tight and cell size near average entity spacing. The per-frame NativeParallelMultiHashMap in 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).
  2. 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.
  3. 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 Wait with a very large value or an infinite Repeater โ†’ Wait โ€” the tree's "completion" semantics are re-run from the root, not "stop".

Known Limitations Summary

LimitationStatus
Retry re-entry hang for custom/composite childrenknown; workaround documented
No cancellation callback for abandoned actionsby 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 agentby design (spatial index)
No Aborted status propagation from user codeAborted is internal (parallel-abort path only)
Editor-only debug state; no profiling overlaysout 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

  1. Unity Package Manager โ†’ Packages โ†’ My Assets โ†’ find Sniveler Code Ai Behavior Architect (see Installation if it isn't there yet).
  2. Click Samples โ†’ Install "DemoWorkers" (or open the package โ†’ Samples tab).
  3. Open the sample's Workers.unity scene (a Landing.unity scene exists too).
  4. 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 under GpuAnimation/ and keep the AiBehavior/ scripts if you only want to study the AI logic.

Scene & Prefab Layout

AssetRole
Scene/Workers.unitythe main sub-scene: bench/workplace layout
Prefabs/WorkPlace.prefaba bench + chest + spawn slot group
Prefabs/HammerWorker.prefaba worker character with BtAgentAuthoring attached (graph assigned in the inspector)
Scripts/AiBehavior/DemoAuthoring.csadds a DemoLodsBuffer (per-worker list of LOD entity ids) to the worker
Scripts/AiBehavior/DemoChestAuthoring.csadds [BtCondition] DemoChestTag to the chest โ€” making it a query target for Find/Condition nodes
Scripts/AiBehavior/DemoBenchAuthoring.csworkplace tagging/components
Scripts/AiBehavior/DemoSpawnerAuthoring.cs / DemoSpawnerSystem.csruntime 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 / DemoBenchAuthoringbench-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:

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

  1. Add a DemoSpawnerAuthoring (or use the scene's existing one) with your target Total (e.g. 1000).
  2. 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.
  3. Use BtSettingsAuthoring's MaxIterationsPerFrame/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

AssemblyFilesWhat they cover
Tests/Editor (SnivelerCode.AiBehavior.Tests.Editor)BtCompilerIntegrationTests.csBtCompiler.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.csStage-1 generation: SystemsNote.g.cs content, registry JSON, asmdef emission, content-hash gating (no rewrite when unchanged)
BtGraphUtilsTests.csGraph editing utilities (link/port helpers, root detection)
BtSettingsTests.csBtSettings defaults, Instance asset creation, authoring bake values
Tests/Runtime (SnivelerCode.AiBehavior.Tests)BtRuntimeLogicTests.csruntime logic exercised in-world: runner transitions, decorator semantics, blackboard condition/modify operators (including the 0.001 epsilon), wait/delay/completion paths
BtParallelDeactivationTests.csthe Parallel-abort path: a running custom action under an abandoned branch receives a deactivation request (Tag disabled) โ€” the guarantee described in Composites
BtUtilsTests.csBtUtils helpers (hashing, prefab resolution)

Running the Tests

  1. Unity โ†’ Window โ†’ General โ†’ Package Manager โ†’ Testing (or install Packages โ†’ Testing if absent).
  2. 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.
  3. 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:

Your responsibility (not covered by the package tests):

Recommended Regression Checks When Upgrading

  1. Run the package's full test suite after upgrading the package (behavior changes land with changelog entries; tests catch regressions).
  2. Re-bake all agent scenes (BtAgentAuthoring bakes at bake time โ€” a package upgrade changes generated code, so a re-bake picks up new system behavior).
  3. 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.

Edit on GitHub v1.0.0