百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
M

MonoBehaviourTree

> 编程语言
开源

适用于 Unity 项目的简单事件驱动行为树

329 stars0 点赞2 次浏览
访问官网GitHub

工具介绍

适用于 Unity 项目的简单事件驱动行为树

MonoBehaviourTree — Simple behaviour tree for Unity

This project is simple event driven behaviour tree based on Unity engine component system. This asset comes with minimal node library and tree visual editor.

Important: This is not fully fledged visual scripting tool. Package has its own visual editor, however requires you to implement your own nodes.

Contribute

Contribution in any form is very welcome. Bugs, feature requests or feedback can be reported in form of Issues.

Getting started

The latest version can be installed via package manager using following git URL: https://github.com/Qriva/MonoBehaviourTree.git#upm

Alternatively you can copy the Assets/MonoBehaviourTree folder to your project or download from Unity Asset Store.

Examples of usage are available in package manager or in folder Samples containing demo scenes. If you copy assets manually you might want to delete Samples directory to get rid of redundant files.

This documentation assumes you have basic knowledge about behaviour trees. If you don't have it, you should check some online resources like this Game Developer article or Unreal Engine documentation.

Event Driven Behaviour Tree Overview

Standard behaviour tree design assumes three types of nodes: composites, decorators and leafs. Composites are used to define the flow in the tree, decorators can modify node results and leafs perform tasks or check conditions. This design has one major flaw - tree must be traversed from the beginning every single tick, otherwise it will not be possible to react to changes in state or data. Event driven tree is the fix to that problem. When tree gets update it continues from the last executed running node. Normally it would mean, that executed higher priority nodes will not be reevaluated immediately, but event driven BT introduces abort system to give possibility to reset tree to previous state, when certain event occur. Implementation used in this project is very similar to the one used in Unreal engine - leaf nodes are not used as conditions, instead they are in form of decorators. Additionally it is possible to create Service nodes which can perform task periodically.

Node Abort

When the tree is updated, the first evaluated thing are aborting nodes. If there is any aborting node, the tree will be reset to that position and execution will be continued from this node. In case there are multiple aborting nodes, the one closest to root will be selected. There are four abort types:

  • None - don't do anything when change occurs
  • Self - abort children running below
  • Lower Priority - abort running nodes with lower priority (nodes to the right)
  • Both - abort self and lower priority nodes

Execution order (priority) of nodes with common ancestor is defined by position on X axis, nodes to the left has higher priority.

Aborts can be performed only by Decorator nodes. See example abort implementation in Decorator section.

Basic Usage

The main core of behaviour tree is MonoBehaviourTree component. It contains most of tree state during runtime. It is important to note, that tree does not run automatically and must be updated by other script. This design gives you possibility to tick the tree in Update, FixedUpdate or custom interval. However, most of the time Update event will be used, so you can use component MBT Executor to do that.

In most of cases you will need some place to store shared data for nodes. You could implement your own component to do that, but instead it's better to use built in Blackboard component. Blackboard allows you to create observable variables of predefined types that are compatible with default nodes.

Node editor

To open tree editor window click "Open editor" button of MonoBehaviourTree component or click Unity menu: Window / Mono Behaviour Tree. In visual editor you can create, connect, delete and setup nodes.

Every behaviour tree needs an entry point called Root. To add it right click on empty canvas to open node popup, then select Root. Execution of BT starts here and goes from top to down, left to right.

Implementation note: All nodes and variables are in fact components, but they are invisible in inspector window. It is recommended to use separate empty game object to build the tree - this make it easier to create prefabs and avoid unnecessary unknown problems.

Most of nodes has additional properties that you can change. To do this select the node and list of options will show up in MonoBehaviourTree component inspector section (standard component inspector). When node setup is not valid, error icon will be shown next to the node. By default error is displayed if one of variable references is set to "None". You can create custom validation rules in your own nodes, see Node API section.

Editor Window Features

Right click on empty space to create new node. To connect nodes click on in/out handler (black dot on top and bottom of node), then drag and drop it above another node. In case node cannot have more than one child (decorator) the connection will be overridden by the new one. To delete, duplicate or disconnect nodes right click on node to open context menu and select the appropriate option. Use left mouse button to drag workspace or nodes. You can drag whole branch of nodes when CTRL key is pressed.

Component Reference

MonoBehaviourTree component

Main component used as hub of behaviour tree.

Properties

  • Description - optional user description.
  • Repeat OnFinish - whether the tree should be executed again when finished.
  • Max Executions Per Tick - how many nodes should be executed during single update.
  • Parent - parent reference if this tree is subtree. Read more in Subtree node section.

Node Inspector - Inspector of node selected in Behaviour Tree editor window.

Blackboard component

Component used to provide and manage observable variables. To add variable fill the Key text field, select it's type and press "Add" button. Key is used as identifier to get or set variable value, this can be done by VariableReference or blackboard method: public T GetVariable(string key). Blackboard component displays all available variables in list and allows to set initial value for each of them.

Implementation note: Changing blackboard variables during playmode triggers change listeners, however old and new value will be the same in this event, because it's called from OnValidate. Displayed values are refreshed every half second.

Built In variable types: Bool, Float, Int, Object, Quaternion, String, Transform, Vector2, Vector3. If you need to add your own custom type read Custom Variable section.

Master Blackboard option allows to make synchronisation effect between variables. When set, blackboard will replace variables during initialization, but only when their keys match. Replacement is not hierarhical and only variables from given parent blackboard are matched. It is recommended to create one master blackboard on top of the tree and keep all other subtrees blackboards synchronized with the top one.

Variables and Events

In most of situations nodes need to share some state data between each other, it can be done by Blackboard, Variable and VariableReference system. Variables are observale data containers, that can be accesed via Blackboard. To get variable you need to know its key, but inputting key manually to every node is not handy and very error prone.

To avoid this you can use helper class VariableReference. This class allows you to automaticaly get and cache reference to blackboard variable. VariableReference has also constant value mode in case you don't need to retrive values from blackboard. You can toggle VarRef mode in editor by clicking small button to the left. Keys displayed in dropdown will be loaded from blackboard on the same object or if there is none it will look upwards the hierarchy to find one.

…

Important: TransformVariable change listener will be called only when reference to object changes. Position or rotation changes do not trigger change listener.

Custom Variable

If built in variables are not enough, you can create your own. To create new Variable and VariableReference you must extend Variable class and VariableReference class. Variable inheriths MonoBehaviour, so to work properly it must by placed in file of the same name as your custom type. VariableReference is normal serializable class and can be placed in the same file. Add [AddComponentMenu("")] attribute to disallow adding variable component manually.

Any variable must implement ValueEquals method which is used to detect change of value. This mechanism allows to correctly compare Unity objects in generic class, avoid boxing, plus gives the way to implement your own change detection logic when needed.

csharp
[AddComponentMenu("")]
public class CustomVariable : Variable
{
    protected override bool ValueEquals(CustomType val1, CustomType val2)
    {
        return val1 == val2;
    }
}

[System.Serializable]
public class CustomReference : VariableReference
{
    // You can create additional constructors and Value getter/setter
    // See FloatVariable.cs as example

    // If your variable is reference type you might want constant validation
    // protected override bool isConstantValid
    // {
    //     get { return constantValue != null; }
    // }
}

Node Reference

Root

Entry node of behaviour tree.

Sequence

Executes children from left to right as long as each subsequent child returns success. Returns success when all children succeeded, or failure if one of them failed. When Random option is enabled, then execution goes in random order.

Selector

Executes children from left to right until one of their children succeeds. Returns success if any children succeed, or failure if all of them failed. When Random option is enabled, then execution goes in random order.

Is Set Condition

Checks if blackboard variable is set. Node supports Bollean, Object and Transform variables. Selecting Invert option will produce "If not set" effect.

Number Condition

Checks if blackboard number variable meets requirement. Node supports Float and Int variables.

Distance Condition

Checks distance between two transforms and returns success when given distance condition is met.

Cooldown

Blocks execition until the specified amount of time has elapsed. Time starts counting after branch is exited. If abort is enabled, the execution will be moved back to this node after time has elapsed.

Force Result

Forces success or failure.

Inverter

Inverts node result. Failure becomes Success and vice versa.

Invoke Unity Event

Triggers Unity Event with one parameter of selected type

Random Chance

There is fixed chance that node will be executed. Returns Failure if roll is not favorable.

Random Float

Generates random float in provided range.

Random Integer

Generates random integer in provided range.

Repeat Until Fail

Repeats branch as long as Success is returned from the child. Use Loop node to create a more advanced flow.

Repeater

Repeats branch specified amount of times or infinitely. Use Loop node to create a more advanced flow.

Loop

Repeats branch specified amount of times, infinitely or until selected result is returned. Results and flow can be fully customized.

Set Boolean

Sets blackboard bool variable

Set Number

Sets blackboard int or float variable

Set Object

Sets blackb

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

C#aibehaviour-treeunity

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言