Unity 6 WebGL Gameplay Prototype • Engineering Case Study

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.

Unity 6 (6000.3.9f1)
Universal Render Pipeline (URP)
C# Finite State Machine
Unity AI Navigation (NavMesh)
Unity Input System
TextMeshPro Telemetry
WebGL 2.0 (IL2CPP)

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, and Search.
  • Navigation: NavMeshAgent path 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

Engine & Render PipelineUnity 6000.3.9f1 (URP)
Compiled SceneAssets/Scenes/AINPCLab.unity
Runtime TargetWebGL 2.0 (IL2CPP Wasm)
FSM States Implemented5 States (Flat Enum FSM)
Core NamespaceAINPCLab.AI / .Player / .UI
Unity 6 NPC AI prototype demonstrating real-time transitions between Patrol, Chase, Attack, Retreat, and Search states in the WebGL arena
Real-time capture of the Unity 6 WebGL build: the NPC evaluates vision cone geometry, line-of-sight blockers, and player aggression telemetry.

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

  1. Approach the NPCObserve the NPC walking between ordered PatrolPath waypoints while scanning ahead.
  2. Test the Vision ConeEnter the forward vision cone or step within the close hearingRadius behind the NPC to trigger detection.
  3. Break Line of SightDuck behind an interior wall obstacle so HasLineOfSight is blocked by cover.
  4. Trigger Chase & AttackStay in view until the NPC closes within attackRange and fires its laser tracer.
  5. Force Retreat or SearchTap Space repeatedly to spike AggressionScore above the retreat threshold, or hide until losePatience expires into Search.

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

1. Player Signal

PlayerBehaviorTracker

Samples player attacks (RegisterAttack), decays AggressionScore, and tracks player Health & DistanceToNPC.

AINPCLab.Player
2. Sensor Queries

NPCSensor Logic

Evaluates hearingRadius, viewRange, viewAngle frustum, and HasLineOfSight against sightBlockers.

CanSensePlayer()
3. Decision Core

NPCBrain (FSM)

Owns CurrentState (Patrol, Chase, Attack, Retreat, Search), ShouldRetreat(), and _lastKnownPlayerPos.

AINPCLab.AI.NPCBrain
4. Actuators

NPCMotor & Combat

Steers NavMeshAgent (MoveToward, StopMoving, FaceTarget) and fires muzzleLaser + knockback in FireAttack().

NavMeshAgent + LineRenderer
5. Telemetry HUD

NPCDebugUI

Read-only observer displaying stateText, aggressionText, distanceText, and healthText.

AINPCLab.UI.NPCDebugUI
Subsystem / ClassImplementation in Prototype BuildCore Responsibilities & Data Flow
PlayerControllerAssets/Scripts/Player/PlayerController.csReads Unity Input System actions (WASD move at walkSpeed / sprintSpeed, Space attack), triggers FlashRed() visual feedback, and notifies PlayerBehaviorTracker.
PlayerBehaviorTrackerAssets/Scripts/Player/PlayerBehaviorTracker.csMaintains AggressionScore (incremented by aggressionPerAttack, decayed by decayPerSecond, clamped to maxAggression) and RecentAttackCount inside ATTACK_WINDOW.
HealthSystem (Player & NPC Heuristic)PlayerBehaviorTracker + NPCBrain.npcHealth01Tracks 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.csExecutes the active state tick (TickPatrol, TickChase, TickAttack, TickRetreat, TickSearch), records _lastSawPlayerAt and _lastKnownPlayerPos, and updates world-space state color/labels.
NPCMotor & PatrolPathAssets/Scripts/AI/PatrolPath.cs + NPCBrain steeringWraps NavMeshAgent velocity/stopping rules (MoveToward, StopMoving, FaceTarget), cycles PatrolPath.waypoints, samples random search points, and selects the farthest retreat transform from safePoints.
CombatSystemNPCBrain.TickAttack() & FireAttack()Enforces attackCooldown, renders the muzzleLaser (LineRenderer) from muzzlePoint for laserFlashDuration, applies knockbackForce impulse, and deals damagePerHit.
NPCDebugUIAssets/Scripts/UI/NPCDebugUI.csDecoupled UI presenter reading NPCBrain and PlayerBehaviorTracker properties to display live state, distance, health, and aggression telemetry without mutating gameplay state.
Why Separate Perception, Decision-Making, and Movement? When sensor queries (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 TriggersEdge Cases Handled
PatrolDefault 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.
ChasePlayer 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() → Retreat
2. DistanceToPlayer <= attackRange & HasLineOfSight() → Attack
3. Time.time - _lastSawPlayerAt > losePatience → Search
Uses a persistence grace window (losePatience) so momentary 1-frame occlusion behind a pillar does not abort pursuit.
AttackPlayer is within attackRange with unobstructed line of sight. Calls StopMoving().Rotates smoothly via FaceTarget(); invokes FireAttack() whenever Time.time - _lastAttackAt >= attackCooldown.1. ShouldRetreat() → Retreat
2. DistanceToPlayer > attackRange or !HasLineOfSight() → Chase
Always re-verifies HasLineOfSight() before firing so the laser never shoots through solid cover.
RetreatTriggered 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.
SearchEntered 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.

Reference C# Structure — NPCBrain.cs State Dispatch & Priority ResolutionUnity 6 (6000.3.9f1)
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:

  1. Distance Check (viewRange): Computes horizontal planar distance (FlatDistance). If the player is beyond viewRange, vision fails immediately without running trigonometry or raycasts.
  2. Angular Frustum Check (viewAngle): Computes the angle (or dot product) between transform.forward and the normalized direction vector to the player. The player must lie within viewAngle * 0.5f degrees of the forward axis.
  3. Obstacle Line-of-Sight Raycast (HasLineOfSight): Casts a ray at eye height from the NPC to the player filtered by the sightBlockers LayerMask. 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.

Unity 6 NPC AI sensor debug view showing forward vision cone and patrol waypoints in the WebGL arena

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() adds aggressionPerAttack to AggressionScore (clamped to maxAggression) and increments RecentAttackCount within a rolling ATTACK_WINDOW. When the player stops attacking, AggressionScore decays continuously by decayPerSecond * Time.deltaTime.
  • Retreat Heuristic (ShouldRetreat): During Chase and Attack, the brain evaluates whether tracker.AggressionScore exceeds aggressionRetreatThreshold. When useHealthHeuristic is enabled, a lower npcHealth01 value scales the effective threshold down so a weakened NPC retreats sooner under player pressure.
  • Hit-Scan Laser & Knockback (FireAttack): In Attack state, the NPC halts movement, rotates via FaceTarget(), verifies HasLineOfSight(), and fires every attackCooldown seconds—rendering a LineRenderer tracer (muzzleLaser) for laserFlashDuration, applying a directional knockbackForce impulse, and calling tracker.RegisterHit(damagePerHit).
Unity 6 NPC AI in Attack state firing a LineRenderer laser tracer at the player after validating line of sight

Attack state: LineRenderer laser tracer + attackCooldown gating.

Practical Combat Scenario: How a 6-Step Encounter Maps to the FSM

1. ApproachPlayer enters the arena while NPC is in Patrol walking between PatrolPath waypoints.
2. DetectionPlayer crosses viewRange inside viewAngle with clear HasLineOfSight().
3. ChaseEnterState(Chase) increases speed to chaseSpeed and tracks _lastKnownPlayerPos.
4. AttackInside attackRange, NPC halts, faces player, and fires muzzleLaser on cooldown.
5. Aggression SpikePlayer presses Space repeatedly; AggressionScore crosses aggressionRetreatThreshold.
6. Retreat → SearchShouldRetreat() triggers Retreat to the farthest safePoint, then transitions to Search.

8. Key Engineering Decisions

Flat Enum FSM vs. Behavior Trees

For an agent with 5 well-defined tactical states, a flat 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

Using a single pre-allocated 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

While Brotli-compressed build files (.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 / ArtifactCategoryValue / StatusVerification Context & Reproducibility
Unity Engine & SceneVerified Build MetadataUnity 6000.3.9f1 (URP) • AINPCLab.unityVerified directly from compiled NPC .data header and global-metadata.dat in repository.
Brotli-Compressed WebGL PayloadMeasured Build Artifact13.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 FilesMeasured Build Artifact59.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 TargetTarget — not independently benchmarkedSingle-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 TargetTarget — not independently benchmarkedSingle planar arena NavMeshSurface asset. Inspect exact serialized byte size in the Unity Inspector on the baked NavMeshData asset.
Frame Rate (60 FPS Target)Optimization TargetTarget — not independently benchmarkedGoverned 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 TargetTarget — not independently benchmarkedImportant 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, and NavMeshAgent pathfinding markers, verifying zero GC.Alloc bytes during steady state switches.
  • In WebGL Browser Builds: Record a 10-second trace in Chrome DevTools (Performance tab) while triggering Patrol → Chase → Attack → Retreat → Search to 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

Instead of every NPC running 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

Calling _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

When one squad member confirms 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

When agents scan for multiple destructible targets or allies, use Physics.OverlapSphereNonAlloc with a pre-allocated Collider[] array to avoid managed heap allocations and GC spikes.

5. Agent & VFX Object Pooling

Pre-warm NPC prefabs and projectile/laser effects using Unity's UnityEngine.Pool.ObjectPool<T> API so wave spawns never stall the main thread with Instantiate calls.

6. Distance-Based AI LOD

Reduce tick frequency and disable 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.

Custom Unity AI & Gameplay Engineering

Discuss an AI Gameplay Project

Need adaptive NPCs, enemy AI, or scalable gameplay systems in Unity? I design and integrate custom AI systems for mobile, desktop, and WebGL games.