Key Takeaways
At Boundev, we build game AI systems for indie studios and enterprise game teams alike. We have shipped FSM-based AI in mobile titles running on 60 FPS budgets with 200+ simultaneous NPCs, and we have built hybrid FSM/Behavior Tree architectures for open-world games with complex faction systems. The FSM is not the "simple" option — it is the foundational pattern that every game AI engineer must master before reaching for more complex alternatives.
Anatomy of a Finite State Machine
An FSM consists of four components that together define the complete behavioral repertoire of an NPC. Understanding these components is essential before writing any C# implementation code.
The State Pattern in C#
The naive approach to FSMs uses enums and switch statements, which quickly becomes unmaintainable as state count grows. The State design pattern solves this by encapsulating each state’s logic into its own class that implements a common interface.
State Pattern Architecture
The three lifecycle methods that define every state in a clean FSM implementation.
1IState Interface
Define a C# interface with Enter(), Execute(), and Exit() methods. Every state class implements this interface, ensuring consistent lifecycle management across all behaviors.
2Enter() — State Initialization
Called once when transitioning into this state. Use it to set animations, initialize variables, start timers, or configure NavMeshAgent destinations. Example: PatrolState.Enter() picks the next waypoint.
3Execute() — Per-Frame Logic
Called every frame (or on a fixed tick interval) while this state is active. Contains the core behavior logic and transition condition checks. Example: ChaseState.Execute() moves toward player and checks attack range.
4Exit() — State Cleanup
Called once when leaving this state. Use it to stop animations, release resources, reset timers, or clean up state-specific data. Example: AttackState.Exit() stops the attack animation coroutine.
FSM vs Behavior Trees vs GOAP
Choosing the right AI architecture depends on the complexity of your NPC behaviors, your target platform’s performance budget, and your team’s familiarity with each pattern. We use all three across our staff augmentation game projects.
Game AI Architecture at Scale
Performance benchmarks for FSM-based AI across Unity target platforms.
Solving the State Explosion Problem
The primary limitation of flat FSMs is that N states can require up to N² transitions to fully connect, making maintenance increasingly difficult as behavior complexity grows. Two proven solutions address this problem.
Hierarchical FSM (HFSM)
- ●Nest sub-state machines inside parent states
- ●Combat state contains Attack, Block, Dodge sub-states
- ●Parent transitions apply to all children automatically
- ●Reduces N² transitions to manageable clusters
Hybrid FSM + Behavior Tree
- ●FSM handles high-level state transitions
- ●Behavior trees manage complex logic within states
- ●Best of both: FSM simplicity + BT modularity
- ●Used in open-world RPGs and strategy games
Ship Game AI That Scales
Boundev’s software outsourcing teams build production game AI — from FSM-driven mobile NPCs to hybrid architectures for open-world titles — with the performance optimization and code quality your players demand.
Talk to Our Game EngineersProduction Architecture Patterns
Common FSM Anti-Patterns:
Production Best Practices:
Boundev Insight: Running FSM updates at 10 Hz instead of 60 Hz reduces AI CPU overhead by 83% with no perceptible difference in NPC behavior quality. We implement this as a configurable tick rate on the StateMachine component, allowing designers to tune individual NPC types based on their gameplay importance.
FAQ
What is a finite state machine in Unity?
A finite state machine (FSM) in Unity is a design pattern for controlling NPC and game object behavior by defining a set of discrete states (like Patrol, Chase, Attack) with conditional transitions between them. Only one state is active at any time, and the active state determines what the game object does each frame. FSMs are implemented in C# using either enum/switch patterns (simple cases) or the State design pattern (production code), where each state is its own class implementing an IState interface with Enter(), Execute(), and Exit() methods.
When should I use FSM vs behavior tree in Unity?
Use an FSM when your NPC has fewer than 12 distinct states, you need maximum performance (mobile/console with many agents), or behavior is relatively linear and predictable. Use a behavior tree when you need 15+ behaviors with complex priority logic, reusable behavior subtrees across multiple NPC types, or when designers need visual editors to configure AI. For complex games, consider a hybrid: FSM for high-level state management (Peaceful, Alert, Combat) with behavior trees handling detailed logic within each state.
How do I prevent state explosion in FSMs?
State explosion occurs when N states produce up to N-squared transitions, making the system unmanageable. Prevent it with hierarchical FSMs (HFSMs) that nest sub-state machines inside parent states, reducing the transition graph to manageable clusters. For example, a Combat parent state containing Attack, Block, and Dodge sub-states means fleeing from combat only requires one transition from Combat to Flee, rather than three separate transitions from each combat sub-state. Additionally, use a centralized transition table rather than hardcoded transitions in each state class.
How many NPCs can FSMs handle in Unity?
A well-optimized FSM can handle 500+ concurrent NPC agents at 60 FPS on mobile hardware. Each FSM update costs approximately 0.02ms per agent. The key optimization is running FSM logic on a fixed tick rate (10–15 Hz) instead of every frame, which reduces CPU overhead by 83% while maintaining perceptually smooth behavior. Memory footprint is approximately 72 bytes per FSM agent (state reference plus context data), making FSMs the most memory-efficient AI architecture available in Unity.
What is GOAP and when should I use it instead of FSM?
Goal-Oriented Action Planning (GOAP) is an AI architecture where agents are given goals and a set of available actions with preconditions and effects, and a planner dynamically determines the optimal action sequence. Use GOAP instead of FSM when you need emergent, unpredictable AI behavior (tactical shooters like F.E.A.R.), when NPCs must dynamically adapt to novel situations, or when the combination of possible behaviors is too large for manual state/transition definition. GOAP is significantly more complex to implement and computationally expensive, making it unsuitable for mobile targets or scenarios with hundreds of concurrent agents.
