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

Implementing A* Search for Plan Generation

Apply the A* pathfinding algorithm to navigate the space of possible world states to reach a desired goal state.

In this lesson, you will learn how to treat your AI’s "planning" process as a pathfinding problem, using A* to navigate from a current world state to a goal state.

Thinking in States

In previous lessons, we defined atomic actions with preconditions (what must be true to act) and effects (how the world changes after an action). To generate a plan, we don't just look for a path on a navmesh; we look for a sequence of actions that transforms our WorldState from "Idle" to "Goal Achieved."

Think of each WorldState as a node in a graph. An action is an "edge" that connects one state to another. A* search finds the sequence of actions that minimizes the "cost" (e.g., time or energy expended) to reach the objective.

Implementing the Search

Your A* algorithm will maintain two lists: Open (states to explore) and Closed (states already visited). The f-score is calculated as g(n) + h(n):

  • g(n): The actual cost of actions taken to reach the current state.
  • h(n): The heuristic estimate of the cost remaining to reach the goal (e.g., how many preconditions are still unsatisfied).
// Conceptual Planner Loop
while (openList.Count > 0) {
    State current = GetBestState(openList);
    if (current.Equals(goalState)) return ReconstructPlan(current);

    foreach (Action action in possibleActions) {
        if (action.PreconditionsMet(current)) {
            State nextState = action.ApplyEffects(current);
            float gScore = current.g + action.cost;
            if (gScore < nextState.g) {
                nextState.parent = current;
                nextState.g = gScore;
                nextState.f = gScore + Heuristic(nextState, goalState);
                openList.Add(nextState);
            }
        }
    }
}

By iterating through these transitions, the AI "simulates" multiple possible futures. It rejects paths that are too costly or impossible, eventually returning the most efficient chain of Action nodes. This allows your AI to handle complex tasks—like "Repair Generator"—by automatically chaining sub-tasks like "Find Tool," "Move to Generator," and "Use Tool" based on the current blackboard data.

Key Takeaway: Plan generation is simply A search applied to an abstract state-space, where edges represent actions and nodes represent snapshots of your blackboard’s world state.*