How NPCs work in Sandbox
mainNPCs operate on a tick-based thinking loop consisting of three stages:
- Senses: The NPC gathers perceptions (visible/audible stimuli, disturbances) into an
Awarenessflag set. - Decision Making: The
GetSchedule()method is called to select the highest-priority behavior that applies to the current state. - Execution: The active schedule executes a sequence of tasks (e.g., moving, looking, firing, or waiting).
Preemption: Higher-priority schedules automatically interrupt lower-priority ones when awareness changes. For example, an NPC will automatically drop a WanderSchedule to engage in a CombatEngageSchedule the moment it detects a threat, meaning you do not need to manually poll for state changes.
/* The NPC thinking loop logic */
// 1. Senses gather awareness
// 2. GetSchedule() picks behavior
// 3. Schedule runs tasks