Course contentsShow
← Unity Game Development
Lesson 567 of 8288. Artificial IntelligenceFree lesson

Debugging Complex Utility-Based Decision Trees

Utilize visual debugging tools to inspect real-time utility scores and trace exactly why an NPC chose a specific action over others.

In this lesson, you will learn how to build real-time visual inspectors to diagnose why your NPC chose a specific action within a complex utility-based decision tree.

When dealing with dozens of weighted factors, "why did the AI do that?" often becomes a difficult question to answer. A utility-based system might choose "Flee" over "Attack" because of a tiny, overlooked modifier in your dynamic game context. To debug this, you must move beyond simple console logs and create an inspector that displays the Utility Breakdown for every available action.

Implementing the Utility Inspector

Instead of just returning a final score, structure your evaluators to store their last calculated values. You can then use OnDrawGizmos or a custom Editor window to visualize the "decision math."

Consider this simplified snippet for tracking score contributions:

public class ActionEvaluator : MonoBehaviour {
    public string actionName;
    public float lastTotalScore;
    public Dictionary<string, float> lastFactors; // Stores component scores

    public float Evaluate() {
        lastFactors.Clear();
        // Calculate each weighted factor (e.g., "Health", "Distance")
        // Store individual results in lastFactors for visualization
        lastTotalScore = ...; 
        return lastTotalScore;
    }
}

Visualizing the Decision

To debug effectively, draw these scores directly above the NPC in the Scene view using Handles.Label. When the AI picks an action, highlight that label in green and show the competing actions in red, including their final lastTotalScore.

If your NPC is behaving erratically, look at the lastFactors list. Is the "Hunger" factor dominating even when the NPC is full? By visualizing the decision tree in real-time, you can immediately identify if a specific normalization curve is returning an unexpected value, or if a dynamic modifier (like a stealth visibility penalty) is improperly scaling an action’s weight. By exposing the raw math that leads to the final "winner," you transform a black-box AI into a transparent system where every decision is verifiable.

Key Takeaway: Never rely on static logs; build a visual debug layer that exposes the individual component scores of your utility calculations to instantly identify which factor caused an unexpected decision.