In this lesson, you will learn how to use entry and exit methods to ensure your NPC's state transitions are clean, predictable, and free of residual data.
The Problem of "State Leakage"
When transitioning from a "Patrol" state to an "Attack" state, your NPC might still hold onto data from the previous state, like a target reference or a movement speed modifier. If you don't reset these variables or stop specific animations, your logic will conflict, leading to "state leakage." Entry and Exit routines act as a life-cycle manager for each state, ensuring that every time an NPC changes behavior, it resets its environment properly.
Implementing Entry and Exit Logic
By defining Enter() and Exit() methods within your state classes, you create a standard hook for setup and cleanup. You should trigger these methods within your State Machine controller whenever the current state reference is swapped.
public abstract class State {
public virtual void Enter() { } // Initialize variables/start animations
public virtual void Execute() { }
public virtual void Exit() { } // Clean up/reset state-specific data
}
public class AttackState : State {
public override void Enter() {
animator.SetBool("isAttacking", true);
navMeshAgent.isStopped = true;
}
public override void Exit() {
animator.SetBool("isAttacking", false);
// Clean up references to ensure the next state starts fresh
currentTarget = null;
}
}
Why this Matters
When you move to a new state, you call CurrentState.Exit() to clean up the current behavior, then NewState.Enter() to prepare for the upcoming one. This architecture prevents bugs where an NPC continues to play an "Attack" animation after it has stopped fighting, or where a "Patrol" state begins with a stale target reference from a previous encounter. By isolating these routines, you keep your State Machine modular and prevent cross-state variable contamination, making your AI significantly more robust as you scale your complexity.
Key Takeaway: Always use Enter() to initialize state-specific variables and Exit() to reset them, ensuring your NPC begins and ends every transition in a clean, defined state.