Build a modular Unity enemy AI with a behavior tree or state machine
Produces a decoupled Unity C# enemy AI driven by a behavior tree or finite-state machine with reusable nodes, inspector-tunable decision weights, and clean extension points for new behaviors.
You are a senior Unity C# AI programmer who builds composable, debuggable enemy behavior. Enemy brief: [DESCRIBE THE ENEMY AND WHAT IT MUST DO — e.g. 'a melee guard that patrols waypoints, chases the player on sight, attacks in range, and flees when below 30% HP']. Architecture preference: [BEHAVIOR TREE / FINITE STATE MACHINE — pick one and say why it fits the brief]. Constraints: - Unity version: [2022 LTS / Unity 6]. - Use the pattern end to end: if a behavior tree, real Selector and Sequence nodes with Success/Failure/Running returns; if an FSM, explicit state classes and transitions, not an enum switch inside Update(). - Decouple sensing from action: a Sensor component (sight range, FOV, hearing) feeds data to the brain; the brain never reaches into the player transform directly. - Expose every tunable (sight range, FOV, attack range, cooldowns, flee threshold, decision tick rate) as [SerializeField] private fields with [Header] groups and sensible defaults. - Use a decision tick (e.g. re-evaluate every 0.1 to 0.2 seconds), not every frame, and cache Transform references. - Include a clear extension point so I can drop in a new behavior node or state without touching the core. Output: 1. A 3-bullet design rationale: why this pattern, where the seams are for extension. 2. Each class as its own fenced code block, file name as a comment on line 1. 3. A wiring note: which GameObjects or components hold the Sensor, the Brain, and the Motor, and how they communicate. 4. A tuning-first checklist: the first values to tweak to change how the enemy feels. State every architecture assumption up front. If the brief is ambiguous, choose a sensible default and flag it. Success signal: the output is good only if sensing is decoupled from the brain, the chosen pattern is used end to end (not a switch-statement shortcut), and every tunable is serialized with a default.
Use case
Use when an enemy needs more than a single Update branch (patrol, chase, attack, flee) and you want behaviors you can add and rebalance without rewriting a god-class.
When to use this
For combat or NPC AI in 3D or 2D. State whether you prefer a behavior tree (composable, prioritized) or a simpler FSM (few states).
Follow-up prompts
- Add a 'hear noise' sense that injects a high-priority Investigate node.
- Move detection tunables into a ScriptableObject so designers define enemy archetypes.
- Add Gizmos to visualize sight cones and the current active node in the Scene view.
- Source
- promptfork seed
- License
- CC-BY-4.0
- Published
- 6/22/2026