In this lesson, you will learn how to reduce the computational overhead of your GOAP (Goal-Oriented Action Planning) system by caching world states to avoid redundant calculations during plan generation.
The Problem: Re-calculating the World
When your AI agent searches for a plan using A*, it evaluates potential actions by simulating their effects on the "World State." If your WorldState object is complex—for example, calculating the distance to every object in the scene or checking recursive sensory data—performing these calculations inside the inner loop of your search algorithm will quickly drop your frame rate, especially when managing multiple NPCs.
The Solution: State Caching
Instead of calculating the world state from scratch every time the planner inspects a node, we use State Caching. We represent the world as a lightweight structure (often a Dictionary or Bitmask) that we derive once before the planning search begins. During the search, we propagate this state by applying only the "Effects" of the chosen actions to a copy of the base state.
Here is a simplified look at how you might cache the world state before starting the search:
public class WorldState {
public Dictionary<string, bool> States = new Dictionary<string, bool>();
// Copy constructor for fast duplication during node expansion
public WorldState(WorldState other) {
States = new Dictionary<string, bool>(other.States);
}
}
// Inside your Planner class:
public void GeneratePlan(WorldState currentGlobalState) {
// Cache the current snapshot to ensure the search doesn't
// trigger new sensory calculations during the A* loop
WorldState cachedSnapshot = new WorldState(currentGlobalState);
// Pass the cachedSnapshot to your A* search algorithm
var plan = AStarSearch(cachedSnapshot, goal);
}
Why This Works
By creating a cachedSnapshot at the start of the planning phase, you decouple the search logic from the expensive perception and sensor systems (like your Line of Sight or Spatial Memory). The search algorithm now interacts only with the cached data, which allows it to simulate thousands of action sequences in milliseconds. When the plan is finalized, the agent executes the steps, and the actual sensory systems refresh naturally on the next tick.
Key Takeaway: By decoupling the planner's state from your real-time sensory data using a cached snapshot, you prevent expensive world-state recalculations from bottlenecking your search algorithm.