Debugging AI
AI bugs rarely crash. They look like "the guard just stood there" or "why did it run into the wall?", and by the time you notice, the moment is gone. The fix is always the same: make the AI's state, target, path, scores and senses visible, in the world and over time. This lesson lists the tools each engine gives you and ends with a flight recorder you can build in any engine.
What to draw
| Draw this | Because it answers |
|---|---|
| Current state / running task as text above the head | "What does it think it's doing?" |
| The path and the next waypoint | "Where is it trying to go?" |
| Vision cone, hearing radius, last known position | "What can it sense, and what does it remember?" (Vision Cones, Memory & Awareness) |
| Utility scores or EQS item scores | "Why did it pick that?" (Utility AI) |
| Line-of-sight rays, green for clear and red for blocked | "Why can't it see me?" |
| Cover points, influence values | "Why did it go there?" (Influence Maps) |
Make every one of these toggleable per category and per agent (debug only the selected enemy), and compile them out of shipping builds.
Unity
using UnityEngine;
public class GuardDebug : MonoBehaviour
{
public float viewDistance = 12f, halfAngle = 50f;
public Vector3 lastKnownPosition;
public string stateName = "Patrol";
void OnDrawGizmosSelected() // only for the selected object
{
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere(lastKnownPosition, 0.3f);
Vector3 left = Quaternion.Euler(0, -halfAngle, 0) * transform.forward;
Vector3 right = Quaternion.Euler(0, halfAngle, 0) * transform.forward;
Gizmos.DrawLine(transform.position, transform.position + left * viewDistance);
Gizmos.DrawLine(transform.position, transform.position + right * viewDistance);
#if UNITY_EDITOR
UnityEditor.Handles.DrawWireArc(transform.position, Vector3.up, left, halfAngle * 2, viewDistance);
UnityEditor.Handles.Label(transform.position + Vector3.up * 2.2f, stateName);
#endif
}
public void DebugRay(Vector3 from, Vector3 to, bool clear) =>
Debug.DrawLine(from, to, clear ? Color.green : Color.red, 0.5f); // stays visible for 0.5 s
}OnDrawGizmos / OnDrawGizmosSelected draw in the Scene view (and in the Game view when its Gizmos toggle is on). Debug.DrawLine can be called from gameplay code with a duration. The AI Navigation overlay shows navmeshes and agent paths, and the Behavior graph editor shows live node status (Unity: AI Navigation & Behavior). Wrap hot AI code in a ProfilerMarker (Unity.Profiling) so it shows up by name in the Profiler window.
Unreal
DrawDebugLine,DrawDebugSphere,DrawDebugCone,DrawDebugString(fromDrawDebugHelpers.h) draw in the world for a duration.- The Gameplay Debugger (apostrophe key during play) shows the nearest AI's behavior tree, blackboard, EQS results, perception and navmesh, toggled per category with the numpad.
- The Visual Logger (Tools > Debug > Visual Logger) records text and shapes per actor during a session; afterwards you scrub a timeline and see exactly what an AI logged at any moment. It is the best tool for "it happened once, five minutes in".
- Unreal Insights profiles CPU time; mark AI code with
TRACE_CPUPROFILER_EVENT_SCOPE.
#include "DrawDebugHelpers.h"
#include "VisualLogger/VisualLogger.h"
void AGuardAIController::DebugDraw(const FVector& Eye, const FVector& Target, bool bClear)
{
#if ENABLE_DRAW_DEBUG
DrawDebugLine(GetWorld(), Eye, Target, bClear ? FColor::Green : FColor::Red, false, 0.5f);
DrawDebugString(GetWorld(), Eye + FVector(0, 0, 60), StateName, nullptr, FColor::White, 0.f);
#endif
UE_VLOG_SEGMENT(this, LogTemp, Log, Eye, Target, bClear ? FColor::Green : FColor::Red, TEXT("LOS %s"), bClear ? TEXT("clear") : TEXT("blocked"));
UE_VLOG(this, LogTemp, Log, TEXT("state=%s"), *StateName);
}Godot
- Debug > Visible Navigation shows navmeshes and paths at runtime;
NavigationAgent3D.debug_enableddraws one agent's path (Godot: NavigationAgent3D). - In 2D, draw in
_draw()withdraw_line,draw_arcanddraw_string, and callqueue_redraw()when the data changes. - In 3D there's no immediate-mode debug draw API, so use a
Label3Dfor state text and anImmediateMesh(or a debug-draw add-on) for lines. Performance.add_custom_monitor("ai/active_guards", callable)adds your own graph to Debugger > Monitors, next to the built-in navigation counters. The Profiler tab shows script function costs.
A flight recorder
Drawing shows now. Most AI bugs need the last few seconds. A flight recorder keeps a small ring buffer of events per agent and dumps it when something suspicious happens, here "in Chase but hasn't moved for 3 frames". It's the core idea of Unreal's Visual Logger, and it fits in any engine:
using System;
var log = new FlightRecorder(capacity: 6);
string state = "Patrol";
double x = 0, lastX = 0;
int stuckFrames = 0;
double[] doorAt = { 5 }; // a closed door the path goes through
for (int frame = 0; frame < 14; frame++)
{
if (frame == 3) { state = "Chase"; log.Add(frame, "perception: player seen at x=9"); }
double target = state == "Chase" ? 9 : 2;
double next = x + Math.Clamp(target - x, -1, 1);
if (next >= doorAt[0] && x < doorAt[0]) next = x; // blocked by the door
log.Add(frame, quot;state={state} x={x:F0} next={next:F0}");
lastX = x; x = next;
stuckFrames = state == "Chase" && x == lastX ? stuckFrames + 1 : 0;
if (stuckFrames == 3)
{
Console.WriteLine(quot;frame {frame}: STUCK in {state}; last {log.Count} events:");
log.Dump();
break;
}
}
class FlightRecorder
{
readonly string[] items; int next;
public int Count { get; private set; }
public FlightRecorder(int capacity) => items = new string[capacity];
public void Add(int frame, string text)
{
items[next] = quot;[{frame,2}] {text}";
next = (next + 1) % items.Length; // overwrite the oldest
Count = Math.Min(Count + 1, items.Length);
}
public void Dump()
{
for (int i = 0; i < Count; i++)
Console.WriteLine(" " + items[(next - Count + i + items.Length) % items.Length]);
}
}frame 7: STUCK in Chase; last 6 events:
[ 3] perception: player seen at x=9
[ 3] state=Chase x=2 next=3
[ 4] state=Chase x=3 next=4
[ 5] state=Chase x=4 next=4
[ 6] state=Chase x=4 next=4
[ 7] state=Chase x=4 next=4
The dump shows the whole story without a debugger: the guard saw the player, chased toward x=9, and the path runs through a closed door at x=5. In a real game you'd also record the path, the blackboard and the seed, and write the dump to a file the QA team attaches to the bug report.
Tip: Recording is cheap (a few strings or structs per frame); drawing is not. Record always in development builds, draw on demand.
Test yourself
A guard misbehaves once, after several minutes of play, and you didn't see it happen. Which tool helps most?
- A breakpoint in Update
- A recorder like Unreal's Visual Logger that you can scrub back through
- Increasing the frame rate
- Debug.Log in every function
Why limit debug drawing to the selected agent and to toggleable categories?
- Engines can draw only one gizmo
- With dozens of agents and every category on, the screen becomes unreadable and drawing costs frame time
- It is required for shipping
- Gizmos only work on selected objects
How do you make AI code show up by name in a CPU profiler?
- Rename the methods
- Wrap it in a profiler scope: ProfilerMarker in Unity, TRACE_CPUPROFILER_EVENT_SCOPE in Unreal
- Run it on another thread
- Use Debug.DrawLine