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

Managing State Transitions With Conditional Triggers

Implement logic gates that detect proximity or sensory data to switch the NPC between active states based on defined gameplay conditions.

In this lesson, you will learn how to bridge the gap between raw sensory data and your State Machine by implementing logical gates that evaluate gameplay conditions before triggering a transition.

The Role of Conditional Triggers

In our modular State Machine architecture, simply detecting an object isn't enough to switch states. An NPC might "see" the player, but if the player is invisible or dead, the NPC shouldn't switch to an AttackState. Conditional triggers act as a gatekeeper, evaluating boolean requirements—or "gates"—before allowing the State Machine to exit the current state.

Implementing the Logic Gate

To keep our code decoupled, we define these requirements as small, reusable classes or ScriptableObject-based data providers. By checking these conditions within an Update loop or an event-driven observer, we can ensure transitions are only initiated when the environment truly demands it.

Consider this snippet, where we verify both proximity (via a RuntimeSet) and a sensory status before transitioning:

public class AttackTrigger : MonoBehaviour
{
    [SerializeField] private PlayerRuntimeSet playerSet;
    [SerializeField] private float attackRange = 5f;

    public bool CanTransition(Transform npcTransform)
    {
        if (playerSet.Items.Count == 0) return false;

        float distance = Vector3.Distance(npcTransform.position, playerSet.Items[0].transform.position);
        bool isTargetInRange = distance <= attackRange;
        
        // Logic Gate: Both conditions must be met to trigger
        return isTargetInRange && !playerSet.Items[0].IsStealthed;
    }
}

Decoupling the Trigger

Instead of hardcoding this check inside your State class, assign this AttackTrigger component to your NPC. Your StateMachine can then reference this trigger as a requirement. This follows our principle of Component-Based Logic Separation, allowing you to swap out sensory conditions (e.g., adding a "Line of Sight" check) without modifying the core state logic. By isolating the condition from the action, you make your AI behavior highly modular and easy to debug. When the CanTransition method returns true, the State Machine executes the state swap, keeping your NPC's decision-making process clean and predictable.

Key Takeaway: Conditional triggers act as a validation layer that protects your state machine from performing transitions based on incomplete or invalid environmental data.