Unity NPC AI System: Adaptive Behavior & NavMesh Architecture
This interactive Unity 6 NPC AI system prototype demonstrates how to build deterministic, responsive enemy behavior without heavy third-party behavior-tree plugins. Built in Unity 6 (`6000.3.9f1` URP) and compiled to WebAssembly (IL2CPP WebGL 2.0), the sandbox solves a core gameplay engineering problem: enabling an NPC agent to perceive player movement, evaluate line-of-sight occlusion, track player aggression over a rolling time window, and transition cleanly between patrol, pursuit, ranged combat, tactical retreat, and search states.
Rather than presenting a standalone single-agent sandbox as a turnkey commercial AI framework, this case study documents the actual C# classes, state-transition rules, spatial queries, and NavMeshAgent steering patterns used in the live build—alongside what changes when scaling this architecture to multi-agent production games.
1. Project Overview
In many Unity prototypes, enemy AI starts as a single monolithic script where distance checks, raycasts, movement transforms, and attack timers are tangled inside one Update() method. As soon as designers add states like searching a last-known position or retreating under heavy fire, state conflicts appear.
This prototype was built to demonstrate a clean separation of concerns across four distinct responsibilities:
- Perception: Vision cone angle/range math, obstacle occlusion linecasts, and close-proximity footstep detection.
- Decision-Making (FSM): Deterministic state transitions across
Patrol,Chase,Attack,Retreat, andSearch. - Navigation:
NavMeshAgentpath requests, safe-point evaluation, and target-facing rotation. - Combat & Telemetry: Hit-scan laser trace feedback, knockback impulses, rolling player aggression scoring, and live HUD diagnostics.
Verified Prototype Specifications

2. Playable WebGL Demo
The WebGL build below is lazy-loaded on click so initial page load and Core Web Vitals remain fast. Click Load Interactive Demo inside the viewport to initialize the Unity 6 WebAssembly runtime.
Load Interactive Demo
Click to initialize the WebGL engine (~15MB). Best experienced on desktop.
Desktop Controls: WASD Move •Left Shift Sprint •Space Attack / Spike Aggression
Note for Mobile Visitors: This sandbox requires a desktop keyboard (WASD + Space) for player movement.
What to Try in the Live Sandbox
- Approach the NPCObserve the NPC walking between ordered
PatrolPathwaypoints while scanning ahead. - Test the Vision ConeEnter the forward vision cone or step within the close
hearingRadiusbehind the NPC to trigger detection. - Break Line of SightDuck behind an interior wall obstacle so
HasLineOfSightis blocked by cover. - Trigger Chase & AttackStay in view until the NPC closes within
attackRangeand fires its laser tracer. - Force Retreat or SearchTap
Spacerepeatedly to spikeAggressionScoreabove the retreat threshold, or hide untillosePatienceexpires intoSearch.
3. System Architecture Breakdown
Inspecting the compiled Assembly-CSharp.dll metadata in the WebGL build shows how the prototype organizes runtime scripts across Assets/Scripts/Player/, Assets/Scripts/AI/, and Assets/Scripts/UI/, and how each logical subsystem maps to the runtime architecture:
Unidirectional Signal Flow: Input → Perception → FSM Brain → Motor / Combat → Telemetry UI
PlayerBehaviorTracker
Samples player attacks (RegisterAttack), decays AggressionScore, and tracks player Health & DistanceToNPC.
NPCSensor Logic
Evaluates hearingRadius, viewRange, viewAngle frustum, and HasLineOfSight against sightBlockers.
NPCBrain (FSM)
Owns CurrentState (Patrol, Chase, Attack, Retreat, Search), ShouldRetreat(), and _lastKnownPlayerPos.
NPCMotor & Combat
Steers NavMeshAgent (MoveToward, StopMoving, FaceTarget) and fires muzzleLaser + knockback in FireAttack().
NPCDebugUI
Read-only observer displaying stateText, aggressionText, distanceText, and healthText.
| Subsystem / Class | Implementation in Prototype Build | Core Responsibilities & Data Flow |
|---|---|---|
| PlayerController | Assets/Scripts/Player/PlayerController.cs | Reads Unity Input System actions (WASD move at walkSpeed / sprintSpeed, Space attack), triggers FlashRed() visual feedback, and notifies PlayerBehaviorTracker. |
| PlayerBehaviorTracker | Assets/Scripts/Player/PlayerBehaviorTracker.cs | Maintains AggressionScore (incremented by aggressionPerAttack, decayed by decayPerSecond, clamped to maxAggression) and RecentAttackCount inside ATTACK_WINDOW. |
| HealthSystem (Player & NPC Heuristic) | PlayerBehaviorTracker + NPCBrain.npcHealth01 | Tracks Health, maxHealth, and HealthPercent via RegisterHit(damage), applying passive health regeneration (healthRegenPerSecond) after regenDelayAfterHit seconds, while NPCBrain evaluates npcHealth01 when useHealthHeuristic is enabled. |
| NPCSensor (Perception Layer) | NPCBrain.CanSensePlayer() & HasLineOfSight() | Combines 360° close-range footstep awareness (hearingRadius) with directional vision cone checks (viewAngle, viewRange) and obstacle occlusion raycasts against sightBlockers. |
| NPCBrain (FSM Decision Core) | Assets/Scripts/AI/NPCBrain.cs | Executes the active state tick (TickPatrol, TickChase, TickAttack, TickRetreat, TickSearch), records _lastSawPlayerAt and _lastKnownPlayerPos, and updates world-space state color/labels. |
| NPCMotor & PatrolPath | Assets/Scripts/AI/PatrolPath.cs + NPCBrain steering | Wraps NavMeshAgent velocity/stopping rules (MoveToward, StopMoving, FaceTarget), cycles PatrolPath.waypoints, samples random search points, and selects the farthest retreat transform from safePoints. |
| CombatSystem | NPCBrain.TickAttack() & FireAttack() | Enforces attackCooldown, renders the muzzleLaser (LineRenderer) from muzzlePoint for laserFlashDuration, applies knockbackForce impulse, and deals damagePerHit. |
| NPCDebugUI | Assets/Scripts/UI/NPCDebugUI.cs | Decoupled UI presenter reading NPCBrain and PlayerBehaviorTracker properties to display live state, distance, health, and aggression telemetry without mutating gameplay state. |
CanSensePlayer) return a pure boolean without directly calling _agent.SetDestination(), you can swap how perception works (for example, adding darkness modifiers or team-shared alerts) or swap how locomotion works (replacing NavMeshAgent with root-motion character controllers) without rewriting the FSM transition rules.4. Finite State Machine (FSM) Design
In NPCBrain.cs, the AI is implemented as a flat, enum-driven Finite State Machine (NPCState) rather than a multi-layer hierarchical state machine (HSM). With five mutually exclusive behavioral states (Patrol, Chase, Attack, Retreat, and Search), a flat FSM avoids heap allocations from state-object instantiation and guarantees that the NPC is in exactly one unambiguous state per frame.
State (NPCState) | Entry Conditions & Setup (EnterState) | Main Behavior (Tick*) | Exit Conditions & Transition Triggers | Edge Cases Handled |
|---|---|---|---|---|
| Patrol | Default initial state or entered after Search timer expires. Sets agent speed to patrolSpeed and indicator color to ColPatrol. | Moves toward patrol.waypoints[_patrolIndex]; advances _patrolIndex cyclically when within waypointReachTolerance. | If CanSensePlayer() returns true → transitions immediately to Chase (or Retreat if ShouldRetreat() is already true). | If patrol is null or has 0 waypoints, the NPC idles cleanly in place while still running perception checks. |
| Chase | Player detected via vision cone or hearing radius, or player moved outside attackRange during combat. Sets speed to chaseSpeed. | Updates _lastKnownPlayerPos while player is sensed and steers toward player position. | 1. ShouldRetreat() → Retreat2. DistanceToPlayer <= attackRange & HasLineOfSight() → Attack3. Time.time - _lastSawPlayerAt > losePatience → Search | Uses a persistence grace window (losePatience) so momentary 1-frame occlusion behind a pillar does not abort pursuit. |
| Attack | Player is within attackRange with unobstructed line of sight. Calls StopMoving(). | Rotates smoothly via FaceTarget(); invokes FireAttack() whenever Time.time - _lastAttackAt >= attackCooldown. | 1. ShouldRetreat() → Retreat2. DistanceToPlayer > attackRange or !HasLineOfSight() → Chase | Always re-verifies HasLineOfSight() before firing so the laser never shoots through solid cover. |
| Retreat | Triggered when ShouldRetreat() returns true. Selects _retreatTarget = PickFarthestSafePoint() and sets speed to retreatSpeed. | Navigates toward _retreatTarget (the safe point maximizing distance from the player) for retreatDuration. | Once retreatDuration elapses (and aggression cools below threshold) → transitions to Search (or Chase if player is still in sight and aggression subsided). | If no safePoints array is assigned, falls back to calculating an opposite-direction escape vector projected onto the NavMesh. |
| Search | Entered when losePatience expires after losing sight of the player. Sets speed to searchSpeed. | Moves to _lastKnownPlayerPos, then picks random NavMesh points (PickNewWanderPoint) within searchWanderRadius. | 1. CanSensePlayer() → Chase (or Retreat)2. Time.time - _stateEnteredAt >= searchDuration → Patrol | Validates random wander candidates via NavMesh.SamplePosition so search targets never land inside walls. |
How Conflicting Transitions Are Resolved
What happens if the player is inside attackRange with clear line of sight at the exact same moment the player's AggressionScore crosses aggressionRetreatThreshold?
NPCBrain resolves conflicts through strict evaluation priority inside TickChase() and TickAttack(): survival (if (ShouldRetreat())) is evaluated first and returns immediately after calling EnterState(NPCState.Retreat), preempting attack execution.
Target Memory & Losing Sight of the Player
Whenever CanSensePlayer() succeeds, the brain records _lastSawPlayerAt = Time.time and caches _lastKnownPlayerPos = player.position.
When the player ducks behind a wall, the NPC continues pursuing toward the last known position for losePatience seconds. Only if the player remains undetected past that window does the NPC transition to Search and sweep a searchWanderRadius circle around _lastKnownPlayerPos.
public enum NPCState { Patrol, Chase, Attack, Retreat, Search }
private void Update()
{
if (_laserHideAt > 0f && Time.time >= _laserHideAt)
{
if (muzzleLaser != null) muzzleLaser.enabled = false;
_laserHideAt = -1f;
}
DistanceToPlayer = FlatDistance(transform.position, player.position);
switch (CurrentState)
{
case NPCState.Patrol: TickPatrol(); break;
case NPCState.Chase: TickChase(); break;
case NPCState.Attack: TickAttack(); break;
case NPCState.Retreat: TickRetreat(); break;
case NPCState.Search: TickSearch(); break;
}
}
private void TickChase()
{
// Priority 1: Survival check preempts pursuit and combat
if (ShouldRetreat())
{
EnterState(NPCState.Retreat);
return;
}
bool sensed = CanSensePlayer();
if (sensed)
{
_lastSawPlayerAt = Time.time;
_lastKnownPlayerPos = player.position;
}
// Priority 2: Engage Attack if within attackRange and unobstructed
if (DistanceToPlayer <= attackRange && HasLineOfSight())
{
EnterState(NPCState.Attack);
return;
}
// Priority 3: Give up to Search if player has been out of sight past losePatience
if (!sensed && (Time.time - _lastSawPlayerAt) > losePatience)
{
EnterState(NPCState.Search);
return;
}
MoveToward(_lastKnownPlayerPos, chaseSpeed, STOP_NEAR);
}5. NPC Perception System
A. Vision Cone & Line-of-Sight Occlusion
Visual detection in CanSensePlayer() executes a three-stage filter ordered from cheapest math to most expensive physics query:
- Distance Check (
viewRange): Computes horizontal planar distance (FlatDistance). If the player is beyondviewRange, vision fails immediately without running trigonometry or raycasts. - Angular Frustum Check (
viewAngle): Computes the angle (or dot product) betweentransform.forwardand the normalized direction vector to the player. The player must lie withinviewAngle * 0.5fdegrees of the forward axis. - Obstacle Line-of-Sight Raycast (
HasLineOfSight): Casts a ray at eye height from the NPC to the player filtered by thesightBlockersLayerMask. If a wall or cover collider intercepts the ray, visual detection is blocked.
B. Hearing / Close-Proximity Footstep Detection
In Unity gameplay programming, it is important to distinguish proximity/collider radius checks from true acoustic wave propagation. A spatial check such as FlatDistance <= hearingRadius (or Physics.OverlapSphere in multi-agent scenes) only detects whether a target collider is inside a spherical radius—it does not simulate sound bouncing around corners or attenuating through walls by itself.
In this prototype, hearingRadius models a 360° close-quarters footstep awareness zone: if the player approaches within hearingRadius behind the NPC, CanSensePlayer() triggers an alert and records _lastKnownPlayerPos even though the player is outside the forward viewAngle cone.
C. Sensor Optimization & Query Budgeting
By gating the Physics.Raycast / Linecast behind distance and angle checks and restricting collisions to the sightBlockers layer mask, the NPC performs at most one physics raycast when the player is inside the vision frustum. When scaling to multiple targets, replace allocating Physics.OverlapSphere calls with pre-allocated Physics.OverlapSphereNonAlloc buffers on a staggered 0.1s–0.2s timer.

Scene capture: NPC traversing PatrolPath while evaluating viewAngle, viewRange, and hearingRadius.
7. Combat & Player Aggression Logic
Instead of making the NPC fight until death in every encounter, PlayerBehaviorTracker and NPCBrain cooperate to create dynamic push-and-pull combat pacing:
- Rolling Aggression Calculation: Whenever the player presses
Space(OnAttack),PlayerBehaviorTracker.RegisterAttack()addsaggressionPerAttacktoAggressionScore(clamped tomaxAggression) and incrementsRecentAttackCountwithin a rollingATTACK_WINDOW. When the player stops attacking,AggressionScoredecays continuously bydecayPerSecond * Time.deltaTime. - Retreat Heuristic (
ShouldRetreat): DuringChaseandAttack, the brain evaluates whethertracker.AggressionScoreexceedsaggressionRetreatThreshold. WhenuseHealthHeuristicis enabled, a lowernpcHealth01value scales the effective threshold down so a weakened NPC retreats sooner under player pressure. - Hit-Scan Laser & Knockback (
FireAttack): InAttackstate, the NPC halts movement, rotates viaFaceTarget(), verifiesHasLineOfSight(), and fires everyattackCooldownseconds—rendering aLineRenderertracer (muzzleLaser) forlaserFlashDuration, applying a directionalknockbackForceimpulse, and callingtracker.RegisterHit(damagePerHit).

Attack state: LineRenderer laser tracer + attackCooldown gating.
Practical Combat Scenario: How a 6-Step Encounter Maps to the FSM
Patrol walking between PatrolPath waypoints.viewRange inside viewAngle with clear HasLineOfSight().EnterState(Chase) increases speed to chaseSpeed and tracks _lastKnownPlayerPos.attackRange, NPC halts, faces player, and fires muzzleLaser on cooldown.Space repeatedly; AggressionScore crosses aggressionRetreatThreshold.ShouldRetreat() triggers Retreat to the farthest safePoint, then transitions to Search.8. Key Engineering Decisions
Flat Enum FSM vs. Behavior Trees
enum FSM in C# requires zero node-graph deserialization, allocates zero heap memory during state switches, and allows instant visual debugging via the world-space state label and HUD.Hit-Scan LineRenderer vs. Pooled Projectiles
LineRenderer (muzzleLaser) toggled on for laserFlashDuration provides immediate visual combat feedback in WebGL without instantiating rigidbody projectiles or extra collider pairs.Static Hosting WebGL Loader Strategy
.br) are generated alongside uncompressed artifacts, the embedded index.html loader references the raw .data and .wasm files so the demo loads reliably across any static CDN or local dev server without failing on missing Content-Encoding: br headers.9. Performance Analysis & Build Artifact Verification
To maintain strict engineering credibility, the table below separates verified build artifacts inspected directly in this repository (public/webgl/ai-npc-system/Build/) from architectural design targets that require live Unity Profiler or browser DevTools captures on your specific hardware.
| Metric / Artifact | Category | Value / Status | Verification Context & Reproducibility |
|---|---|---|---|
| Unity Engine & Scene | Verified Build Metadata | Unity 6000.3.9f1 (URP) • AINPCLab.unity | Verified directly from compiled NPC .data header and global-metadata.dat in repository. |
| Brotli-Compressed WebGL Payload | Measured Build Artifact | 13.0 MB Total (.data.br: 4.9 MB, .wasm.br: 8.0 MB, .js.br: 74 KB) | Measured on disk in public/webgl/ai-npc-system/Build/ (May 2026 release build). |
| Uncompressed Fallback WebGL Files | Measured Build Artifact | 59.4 MB Total (.data: 13.0 MB, .wasm: 46.0 MB, .js: 445 KB) | Loaded by index.html when served without custom Brotli HTTP response headers; subject to standard CDN gzip/brotli transfer compression. |
| Draw Calls (~20 Target) | Optimization Target | Target — not independently benchmarked | Single-arena primitive geometry using URP SRP Batcher. Verify in Unity Frame Debugger or browser Spector.js at 960×600 canvas resolution. |
| NavMesh Surface Data (<50 KB Target) | Optimization Target | Target — not independently benchmarked | Single planar arena NavMeshSurface asset. Inspect exact serialized byte size in the Unity Inspector on the baked NavMeshData asset. |
| Frame Rate (60 FPS Target) | Optimization Target | Target — not independently benchmarked | Governed by browser requestAnimationFrame VSync on desktop GPUs. Measure 95th-percentile frame times via Chrome DevTools Performance panel. |
| Memory Footprint (<50 MB Managed/Asset Target) | Optimization Target | Target — not independently benchmarked | Important Distinction: Refers to internal Unity asset/managed heap budget, not total browser tab process memory (which includes the 46 MB Wasm binary, WebGL graphics buffers, and browser compositor). |
How to Profile This AI System in Unity 6 & Browser DevTools
Because this prototype runs a single NPC agent, per-frame AI CPU cost is minuscule—performing one planar distance calculation, at most one raycast (HasLineOfSight), and one NavMeshAgent destination update per tick. To profile the system yourself (see our Unity 6 Performance & Profiler Guide):
- In Unity Editor / Standalone Development Build: Open the Unity Profiler (CPU Timeline) and inspect
NPCBrain.Update,Physics.Raycast, andNavMeshAgentpathfinding markers, verifying zeroGC.Allocbytes during steady state switches. - In WebGL Browser Builds: Record a 10-second trace in Chrome DevTools (Performance tab) while triggering
Patrol → Chase → Attack → Retreat → Searchto measure JS/Wasm main-thread frame duration and GPU rasterization time.
10. Unity Editor Automation (`AINPCLabBuilder`)
During development of the sandbox scene (Assets/Scenes/AINPCLab.unity), an Editor-only utility script (AINPCLabBuilder.cs, which compiles into Assembly-CSharp-Editor and is automatically stripped from player builds) was used to standardize repeatable scene and build setup tasks:
1. Scene & Waypoint Wiring
Validates that NPCBrain has valid references to the PatrolPath waypoints, safePoints transforms, PlayerBehaviorTracker, and NPCDebugUI text labels before building.
2. Layer & Occlusion Mask Validation
Ensures arena cover walls are assigned to the layers included in NPCBrain.sightBlockers so line-of-sight raycasts never pass through obstacles.
3. NavMeshSurface Rebaking
Triggers a clean NavMeshSurface bake whenever obstacle placement or agent radius settings change in the arena.
4. WebGL Export Preset Verification
Configures WebGL player settings and exports the build artifacts into the public/webgl/ai-npc-system/ directory structure.
11. Technical Challenges & Solutions
Challenge 1: Preventing Rapid State Thrashing at Vision Cone Boundaries
Problem: When the player strafed across the edge of the vision cone or briefly ducked behind a narrow pillar, a naive FSM immediately flipped between Chase and Search every few frames.
Solution: Introduced _lastSawPlayerAt and the losePatience persistence timer in NPCBrain. During Chase, the NPC continues pursuing toward _lastKnownPlayerPos until Time.time - _lastSawPlayerAt > losePatience, smoothing out momentary line-of-sight interruptions.
Challenge 2: Avoiding Corner Traps During Retreat
Problem: Computing a simple backward vector (transform.position - player.position) often backed the NPC straight into a dead-end corner wall when the player attacked near the arena perimeter.
Solution: Added curated safePoints transforms around the arena and implemented PickFarthestSafePoint(), which evaluates all safe anchor points and routes the NavMeshAgent to the safe point maximizing distance from the player's current position.
Challenge 3: Making Search Behavior Feel Intentional Instead of Robotic
Problem: Stopping dead in place as soon as the player broke line of sight made the AI feel unnatural.
Solution: In TickSearch(), the NPC first navigates to _lastKnownPlayerPos and then generates localized investigation points (PickNewWanderPoint()) within searchWanderRadius for searchDuration seconds before returning to its PatrolPath.
12. Scaling from One NPC to Multiple Agents
This WebGL sandbox intentionally runs a single NPC agent so visitors can clearly observe individual state transitions and HUD telemetry. It has not been stress-tested with dozens of simultaneous agents in this build. If you are adapting this architecture for a commercial game with 20 to 100+ active enemies, apply these production scaling patterns:
1. Frame-Staggered Sensor Scheduling
CanSensePlayer() and Physics.Raycast on every frame, assign each agent a modulo frame offset ((Time.frameCount + agentId) % 6 == 0) or register agents with a central AISensorScheduler that budgets a fixed number of raycasts per frame.2. Path Recalculation Throttling
_agent.SetDestination(player.position) every frame across 50 chasing agents floods the NavMesh pathfinder queue. Only request a new path when the target has moved more than a threshold distance (e.g., 0.5m) and !_agent.pathPending.3. Shared Squad Blackboard Alerts
HasLineOfSight(), broadcast the player's _lastKnownPlayerPos to nearby allies via a shared squad blackboard and assign flanking offsets so 10 agents do not crowd the exact same world coordinate.4. NonAlloc Physics Buffers
Physics.OverlapSphereNonAlloc with a pre-allocated Collider[] array to avoid managed heap allocations and GC spikes.5. Agent & VFX Object Pooling
UnityEngine.Pool.ObjectPool<T> API so wave spawns never stall the main thread with Instantiate calls.6. Distance-Based AI LOD
Animator bone skinning (CullUpdateTransforms) for agents far outside the player's camera frustum.13. Frequently Asked Questions
1. How do you build adaptive NPC AI in Unity?
Separate the AI into modular layers: a Perception layer that evaluates vision cone angles, line-of-sight raycasts, and proximity radii; a Behavior Tracker that samples player actions (such as attack frequency or damage output over a rolling time window); a Decision layer (such as a Finite State Machine) that selects the active state; and a Motor/Actuator layer that drives NavMeshAgent movement and combat routines.
2. When should you use an FSM instead of Behavior Trees in Unity?
Use a Finite State Machine (FSM) when an agent has a bounded set of mutually exclusive states (typically 3 to 8 states such as Patrol, Chase, Attack, Retreat, and Search) where deterministic transitions, zero runtime memory allocations, and fast debugging are priorities. Consider Behavior Trees, Hierarchical FSMs, or Utility AI when agents require dozens of composable sub-behaviors, complex parallel sequences, or non-programmer designer authoring trees.
3. How does Unity NavMesh pathfinding work?
Unity's com.unity.ai.navigation package bakes walkable level geometry into a convex polygon mesh (NavMeshSurface). At runtime, calling NavMeshAgent.SetDestination() queues an asynchronous A* search across those polygons to find a corridor of portals, and steers the agent along the smooth string-pulled path while avoiding dynamic obstacles.
4. How can NPCs detect players behind obstacles without cheating?
Combine directional vision with a short-range proximity/hearing radius and target memory. While visual detection requires the player to be inside the forward viewAngle and pass a Physics.Raycast against sightBlockers, a close-range hearingRadius detects footsteps when a player sprints right behind the NPC. Once detected, caching _lastKnownPlayerPos allows the NPC to navigate around the obstacle to investigate where the player was last seen or heard.
5. How do you optimize AI perception on mobile and WebGL?
Filter spatial checks from cheapest to most expensive: check planar squared distance first, then check the vision cone dot product/angle, and only execute a Physics.Raycast (restricted by a specific LayerMask) if both checks pass. For multi-agent scenes, stagger perception ticks across frames and use Physics.OverlapSphereNonAlloc to prevent garbage collection spikes.
6. Can this architecture scale to multiple NPCs?
Yes, with appropriate multi-agent scheduling. While this demo build runs a single NPC agent, the decoupled NPCBrain + PlayerBehaviorTracker design can be scaled by throttling SetDestination calls, staggering sensor raycasts across frames, pooling enemy instances with ObjectPool<T>, and coordinating flank positions through a shared squad blackboard.
7. Can these systems integrate with an existing Unity project?
Yes. Because NPCBrain, PatrolPath, and PlayerBehaviorTracker rely solely on standard Unity 6 packages (UnityEngine.AI, UnityEngine.InputSystem, and TMPro), they can be dropped into existing 3D mobile, desktop, or WebGL projects and hooked up to custom character animators, health components, and weapon systems.