In this lesson, you will learn how to quantify NPC motivation by assigning numerical "utility scores" to possible actions, allowing your agents to choose the most desirable behavior based on their current needs.
Why Use Utility?
While goal-oriented planning tells an NPC how to achieve a goal, Utility-Based AI determines which goal is most important right now. Instead of rigid logic (like "If hungry, eat"), we calculate a score between 0 and 1 for every potential action. The NPC then performs the action with the highest total score, creating nuanced, human-like behavior that shifts fluidly as the environment changes.
Calculating the Score
A utility score is typically a combination of three factors: Need (Internal state), Opportunity (Environmental state), and Efficiency (Cost to perform).
Consider an NPC choosing between "Eat" and "Rest." We define a function for each:
public float CalculateEatUtility(float hunger, bool foodNearby) {
// Hunger acts as our primary multiplier
float hungerFactor = Mathf.Clamp01(hunger / 100f);
// Opportunity multiplier: if no food exists, utility drops to zero
float opportunity = foodNearby ? 1.0f : 0.0f;
return hungerFactor * opportunity;
}
In this snippet, if the NPC is starving (hunger = 100) and food is nearby, the utility is 1.0. If there is no food, the utility is 0.0, regardless of how hungry the NPC feels. This forces the agent to look for food before it can "choose" to eat.
Smoothing the Curves
You can use AnimationCurves in the Unity Inspector to define these utility functions. A linear increase is rarely realistic; you might want the desire for "Rest" to stay low until energy drops below 30%, at which point the utility should spike aggressively. By mapping these curves, you control the NPC's personality—a "lazy" NPC might have a steeper slope for resting, while a "hardworking" NPC might prioritize tasks even when fatigued.
By evaluating these scores every few frames, your NPC naturally transitions from searching for water to finding shelter, effectively prioritizing survival in a dynamic world.
Key Takeaway: Utility scores transform abstract needs into actionable data by mapping environmental variables and internal drives to a normalized 0-1 range, allowing the agent to dynamically select the most impactful behavior.