In this lesson, you will learn how to structure complex NPC logic by implementing Selector and Sequence nodes to govern the flow of your Behavior Trees.
The Logic of Choice vs. Completion
While State Machines handle specific modes of existence, Behavior Trees use Composite Nodes to manage decision-making hierarchy.
-
Selector Nodes (
ORlogic): A Selector attempts its children one by one. If a child succeeds, the Selector returnsSuccessand stops. It is perfect for prioritized tasks. For example, an NPC might have a Selector node with three children:AttackPlayer,HealSelf, andPatrol. It will always try to attack first; if that fails (e.g., the player is too far), it tries to heal; if that fails, it defaults to patrolling. -
Sequence Nodes (
ANDlogic): A Sequence executes its children in order, but only as long as they succeed. If a child fails, the entire Sequence fails. This is ideal for multi-step procedures. For instance, a "Gather Resource" sequence would contain: 1.MoveToResource, 2.PlayGatherAnimation, 3.AddInventoryItem. If the agent cannot reach the resource, the sequence stops immediately, preventing the character from playing the animation in thin air.
Implementation Example
You can define these as objects that return a NodeResult (Success, Failure, or Running). Here is a simplified conceptual structure:
public abstract class Node {
public abstract NodeResult Evaluate();
}
public class Selector : Node {
public List<Node> children;
public override NodeResult Evaluate() {
foreach (var child in children) {
if (child.Evaluate() == NodeResult.Success) return NodeResult.Success;
}
return NodeResult.Failure;
}
}
By nesting these nodes—placing a Sequence inside a Selector—you create a "brain" that can handle complex behaviors. The Selector ensures the NPC picks the most important task, while the Sequence ensures that once that task is picked, the agent performs all the necessary sub-steps to finish it correctly.
Key Takeaway: Use Selectors to prioritize tasks and Sequences to enforce strict step-by-step procedures in your AI's decision-making flow.