SkillAgentSearch skills...

NPBehave

Event Driven Behavior Trees for Unity 3D

Install / Use

/learn @meniku/NPBehave
About this skill

Quality Score

0/100

Supported Platforms

Universal

README

NPBehave - An event driven Behavior Tree Library for code based AIs in Unity

NPBehave Logo

NPBehave aims to be:

  • lightweight, fast & simple
  • event driven
  • easily extendable
  • A framework to define AIs with code, there is no visual editing support

NPBehave builds on the powerful and flexible code based approach to define behavior trees from the BehaviorLibrary and mixes in some of the great concepts of Unreal's behavior trees. Unlike traditional behavior trees, event driven behavior trees do not need to be traversed from the root node again each frame. They stay in their current state and only continue to traverse when they actually need to. This makes them more performant and a lot simpler to use.

In NPBehave you will find most node types from traditional behavior trees, but also some similar to those found in the Unreal engine. Please refer to the Node Type Reference for the full list. It's fairly easy to add your own custom node types though.

If you don't know anything about behavior trees, it's highly recommended that you gain some theory first, this Gamasutra article is a good read.

Installation

Just drop the NPBehave folder into your Unity project. There is also an Examples subfolder, with some example scenes you may want to check out.

Example: "Hello World" Behavior Tree

Let's start with an example:

using NPBehave;

public class HelloWorld : MonoBehaviour
{
    private Root behaviorTree;

    void Start()
    {
        behaviorTree = new Root(
            new Action(() => Debug.Log("Hello World!"))
        );
        behaviorTree.Start();
    }
}

Full sample

When you run this, you'll notice that "Hello World" will be printed over and over again. This is because the Root node will restart the whole tree once traversal bypasses the last node in the tree. If you don't want this, you might add a WaitUntilStopped node, like so:

// ...
behaviorTree = new Root(
	new Sequence(
		new Action(() => Debug.Log("Hello World!")),
		new WaitUntilStopped()
	)
);
///... 

Up until now there really isn't anything event driven in this tree. Before we can dig into this, you need to understand what Blackboards are.

Blackboards

In NPBehave, like in Unreal, we got blackboards. You can think about them as beeing the "memory" of your AI. In NPBehave, blackboards are basically dictionaries that can be observed for changes. We mainly use Service to store & update values in the blackboards. And we use BlackboardCondition or BlackboardQuery to observe the blackboard for changes and in turn continue traversing the bahaviour tree. Though you are free to access or modify values of the blackboard everywhere else (you'll also access them often from Action nodes).

A blackboard is automatically created when you instantiate a Root, but you may also provide another instance with it's constructor (this is particularly useful for Shared Blackboards)

Example: An event-driven behavior tree

Here's a simple example that uses the blackboard for event-driven behavior:

/// ...
behaviorTree = new Root(
    new Service(0.5f, () => { behaviorTree.Blackboard["foo"] = !behaviorTree.Blackboard.Get<bool>("foo"); },
        new Selector(
        
            new BlackboardCondition("foo", Operator.IS_EQUAL, true, Stops.IMMEDIATE_RESTART,
                new Sequence(
                    new Action(() => Debug.Log("foo")),
                    new WaitUntilStopped()
                )
            ),

            new Sequence(
                new Action(() => Debug.Log("bar")),
                new WaitUntilStopped()
            )
        )
    )
);
behaviorTree.Start();
//...

Full sample | More sophisticated example

This sample will swap between printing "foo" and "bar" every 500 milliseconds. We use a Service decorator node to toggle the foo boolean value in the blackboard. We use a BlackboardCondition decorator node to decide based on this flag whether the branch gets executed or not. The BlackboardCondition also watches the blackboard for changes based on this value and as we provided Stops.IMMEDIATE_RESTART the currently executed branch will be stopped if the condition no longer is true, also if it becomes true again, it will be restarted immediately.

Please note that you should put services in real methods instead of using lambdas, this will make your trees more readable. Same is true for larger actions.

Stops Rules

Some Decorators such as BlackboardCondition, Condition or BlackboardQuery have a stopsOnChange parameter that allows to define stop rules. The parameter allows the Decorator to stop the execution of a running subtree within it's parent's Composite. It is your main tool to make power of the event-drivenness in NPBehave.

A lower priority node is a node that is defined after the current node within it's parent Composite.

The most useful and commonly used stops rules are SELF, IMMEDIATE_RESTART or LOWER_PRIORITY_IMMEDIATE_RESTART.

Be careful if you're used to Unreal though. In NPBehave BOTH and LOWER_PRIORITY have a slightly different meaning. IMMEDIATE_RESTART actually matches Unreal's Both and LOWER_PRIORITY_IMMEDIATE_RESTART matches Unreal's Lower Priority.

The following stop rules exist:

  • Stops.NONE: the decorator will only check it's condition once it is started and will never stop any running nodes.
  • Stops.SELF: the decorator will check it's condition once it is started and if it is met, it will observe the blackboard for changes. Once the condition is no longer met, it will stop itself allowing the parent composite to proceed with it's next node.
  • Stops.LOWER_PRIORITY: the decorator will check it's condition once it is started and if it's not met, it will observe the blackboard for changes. Once the condition is met, it will stop the lower priority node allowing the parent composite to proceed with it's next node.
  • Stops.BOTH: the decorator will stop both: self and lower priority nodes.
  • Stops.LOWER_PRIORITY_IMMEDIATE_RESTART: the decorator will check it's condition once it is started and if it's not met, it will observe the blackboard for changes. Once the condition is met, it will stop the lower priority node and order the parent composite to restart the Decorator immediately.
  • Stops.IMMEDIATE_RESTART: the decorator will check it's condition once it is started and if it's not met, it will observe the blackboard for changes. Once the condition is met, it will stop the lower priority node and order the parent composite to restart the Decorator immediately. As in BOTH it will also stop itself as soon as the condition is no longer met.

One caveat with both IMMEDIATE_RESTART variants is currently, that they may not actually always immediately restart your node. They won't immediately restart it in case the aborted branch leads the parent composite to evalutate to succeed. Therefor it's generally advised to make use of stop rules within Selector nodes and return Failed when your nodes are aborted.: In NPBehave 2.0 this might change.

Blackboard Alternatives

In NPBehave you define your behavior tree within a MonoBehaviour, as thus it isn't necessary to store everything in the blackboard. If you don't have BlackboardDecorator or BlackboardQuery with other stop rules than Stops.NONE, you probably don't need them to be in the blackboard at all. You can also just make use of plain member variables - it is often the cleaner, faster to write and more performant. It means that you won't make use of the event-drivenness of NPBehave in that case, but it's often not necessary.

If you want to be able to make use of stopsOnChange stops rules without using the Blackboard, two alternative ways exist in NPBehave:

  1. use a regular Condition decorator. This decorator has an optional stopsOnChange stops rules parameter. When providing any other value than Stops.NONE, the condition will frequently check the condition and interrupt the node according to the stops rule when the result of the given query function changes. Be aware that this method is not event-driven, it queries every frame (or at the provided interval) and as thus may lead to many queries if you make heavy use of them. However for simple cases it is often is sufficient and much simpler than a combination of a Blackboard-Key, a Service and a BlackboardCondition.
  2. Build your own event-driven Decorators. It's actually pretty easy, just extend from ObservingDecorator and override the isConditionMet(), StartObserving() and StopObserving() methods.

Node execution results

In NPBehave a node can either succeed or fail. Unlike traditional behavior trees, there is no result while a node is executing. Instead the node will itself tell the parent node once it is finished. This is important to keep in mind when

Related Skills

View on GitHub
GitHub Stars1.3k
CategoryDevelopment
Updated3h ago
Forks206

Languages

C#

Security Score

95/100

Audited on Apr 3, 2026

No findings