In an NPC finite state machine, what do a state's enter, update and exit actions do, and how does one tick run?
answer
- three hooks per state
- once, every tick, once
- guards tested before update
- exit old, then enter new
basics
~20 sEnter runs once on arriving in a state, update runs every tick while the NPC stays, exit runs once on leaving. Each tick tests the current state's transition guards; when one passes, the old state exits and the new one enters.
solid answer
~50 sA flat NPC finite state machine has one current state, such as `Idle`, `Attack` or `Enraged` for a boss, and transitions, each a guard condition plus a target state. Every state carries three hooks. `enter` runs once on arrival and sets up: play the roar, pick a target, start a timer. `update` runs every tick while the state is current: face the player, swing when the cooldown has elapsed. `exit` runs once on departure and cleans up: cancel a charge, release a reserved attack slot. A common tick order is: test the current state's guards in their listed order; if one passes, call the old state's `exit`, then any action on that transition, then the new state's `enter`; otherwise call `update`. Putting setup and cleanup in enter and exit means every path into or out of a state gets them, rather than each transition copying them.
code
pseudocode · 11 linesfunction tickStateMachine(npc, dt):
current = npc.state
for t in current.transitions: # tested in listed order
if t.guard(npc):
current.exit(npc)
if t.action != null:
t.action(npc)
npc.state = t.target
npc.state.enter(npc)
return # at most one transition per tick
current.update(npc, dt)go deeper
Recall the three hooks and how often each runs: enter once on arrival, update every tick, exit once on departure. Be able to walk one tick for a boss going from Attack to Enraged.
Explain why setup and cleanup live in enter and exit rather than on transitions, and state your tick order explicitly: guards first or update first, and how many transitions may fire per tick.
Show you have debugged hook-ordering bugs: cleanup skipped on a new path, side-effecting guards, a despawn that never ran exit. Say how you would enforce one tick convention across a codebase.
Mostly an implementation question; at lead level, expect to justify a single documented tick and hook contract that every NPC machine and tool in the codebase follows.
## The model A **finite state machine (FSM)** describes an NPC's behaviour as a small set of named **states** and the **transitions** between them. At any moment a flat machine has exactly one **current state**. Take a boss monster: - `Idle`: waits in its arena until the player comes close. - `Attack`: faces the player and swings on a cooldown. - `Enraged`: entered once when health drops below half; faster swings, a new move set. - `Stunned`: stands dazed for a few seconds after a heavy hit. - `Dead`: plays the death sequence and stops deciding. A **transition** is a pair: a **guard** (a yes/no condition such as `health < 0.5 * maxHealth`) and a **target state**. Transitions belong to the state they leave, so `Idle` only asks "is the player within aggro range?", not every question the boss could ever ask. That locality is the main reason FSMs are easy to reason about: in a given state, only a handful of exits exist. ## The three hooks on a state Each state exposes up to three pieces of code, often called **actions** or **hooks**: - **`enter`** runs once, at the moment the machine switches into the state. It does one-time setup: play the enrage roar, choose a target, reset an attack cooldown, start a stun timer. - **`update`** runs on every AI tick while the state stays current. It does the ongoing work: turn towards the player, step forward, trigger a swing when the cooldown has elapsed. - **`exit`** runs once, at the moment the machine leaves the state. It undoes what the state started: cancel a charge that is in progress, release a reserved slot in the attack queue, stop a looping sound. Some designs add a **transition action** that runs between `exit` and `enter` and belongs to one edge rather than to a state. It is the right home for an effect that should happen only on that path, for example a shout played only when the boss goes from `Attack` to `Enraged`, not when it reaches `Enraged` some other way. ## One tick, step by step A common order for one tick of the machine: 1. Take the current state's transitions in their listed order. 2. Evaluate each guard. The first one that passes wins; the rest are not tested this tick. 3. If a transition fired: call the current state's `exit`, then the transition action if any, then set the current state to the target and call its `enter`. 4. If nothing fired: call the current state's `update` with the elapsed time. The pseudocode example on this question follows exactly this order. Two properties are worth noticing. First, at most one transition fires per tick, which rules out a loop of states bouncing within one frame. Second, the state just entered does not get an `update` in the same tick in this version. ## Choices that differ between implementations Neither the hook names nor the tick order are fixed by any standard, and real codebases differ. What matters is choosing one convention and applying it everywhere. | Choice | Option A | Option B | Consequence | |---|---|---|---| | Guards vs update first | Test guards, then update | Update, then test guards | B lets a state act once on the tick it will leave | | Update on the entering tick | Wait for next tick | Run immediately | B avoids a one-tick gap; A keeps per-tick work bounded | | Transitions per tick | One | Several, chained | Chaining needs a cap or two states can loop forever | | Who owns transitions | The source state's list | A central table | A table makes order visible and checkable | ## Why separate the hooks at all The split exists because a state is entered and left along many paths. If cleanup lived on one transition, the first new transition added by a designer would skip it, and the boss would keep a half-finished charge after being stunned. Putting cleanup in `exit` guarantees it runs whichever transition fires. Likewise, setup in `enter` runs whether `Enraged` was reached from `Attack` or from `Stunned`. ## Common mistakes - Doing one-time setup in `update` guarded by a "first frame" flag, which is just a hand-built `enter` that someone eventually forgets to reset. - Giving guards side effects such as playing a sound: a guard may not run at all once an earlier guard passes, so the effect becomes order-dependent. - Assuming `exit` runs when the NPC is destroyed outright; it runs only if the destruction goes through the machine, so despawning should either call it or not rely on it. - Expecting `enter` to run again when a transition targets the state already current: whether a self-transition exits and re-enters is a design choice to make explicitly.
- Should the newly entered state's update run in the same tick it is entered?Either is defensible. Running it at once avoids a one-tick pause, which matters when ticks are infrequent; deferring it keeps each tick's work bounded and the order simple. What breaks things is inconsistency, such as some states assuming their `enter` and first `update` share a tick. Pick one rule, document it and keep it.
- Why should a transition guard never change game state?Guards are queries. Which guards run depends on list order, because testing stops at the first that passes, and debug tools may evaluate guards just to display them. A guard that plays a sound or sets a flag makes behaviour depend on order and on whether someone is watching. Put effects in `exit`, a transition action or `enter`.
- What belongs in a transition action rather than in exit or enter?An effect tied to one particular edge. If the boss should shout only when it enrages mid-fight, but not when it reaches `Enraged` after a stun, the shout belongs to the `Attack` to `Enraged` transition. Effects that must happen on every arrival go in `enter`, and on every departure in `exit`.
- Enter runs every frame while the NPC remains in the state.
- Cleanup only needs to sit on the transition that usually leaves the state.
- A guard can safely play a sound because every guard is evaluated each tick.
- A flat FSM can keep several states current at the same time.
- The tick order of guards and update is fixed by a standard, so it never needs documenting.