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

Resolving Plan Failures and Re-planning

Implement logic to detect when a planned action fails and trigger a new planning cycle to adapt to the environment.

In this lesson, you will learn how to make your AI resilient by detecting when a planned action fails and automatically generating a new strategy to achieve its goals.

The Problem: When Reality Diverges from the Plan

In a GOAP (Goal-Oriented Action Planning) system, your agent builds a sequence of atomic actions to reach a state. However, the world is dynamic. Perhaps your NPC planned to "Pick up Key," but a player moved the key, or a door it intended to walk through is now locked. If the agent continues to follow the "stale" plan, it will effectively "break" or loop uselessly.

Implementing Failure Detection

To resolve this, your AI must monitor the environment during the execution of each step. If a precondition for the current action is no longer met, or if the action returns a Failure state, the AI must abort the current plan and trigger a re-planning cycle.

Here is a simplified approach to handling this in your ActionController:

public void ExecuteCurrentPlan() {
    ActionNode currentAction = planQueue.Peek();

    // Check if the world state still supports the current action
    if (!currentAction.IsPreconditionMet(blackboard)) {
        Debug.Log("Precondition failed! Triggering re-planning...");
        TriggerReplan();
        return;
    }

    if (currentAction.Perform() == ActionStatus.Failure) {
        // If the action itself fails, we must discard the plan
        planQueue.Clear();
        TriggerReplan();
    }
}

The Re-planning Cycle

When TriggerReplan() is called, you don't just want to stop; you want the AI to re-evaluate its current world state and run the A* search algorithm again. By clearing the planQueue and invoking the search function, the agent considers its updated position and the updated state of the environment.

Crucially, ensure your heuristic cost function reflects the current state accurately. If an action failed because a path was blocked, ensure that the pathfinding or spatial memory update marks that area as "costly" or "impassable." This prevents the agent from simply picking the exact same failed plan repeatedly.

Key Takeaway: A robust AI treats a plan as a temporary intention rather than a fixed command, triggering a new search whenever its environmental preconditions are violated or an action fails.