适用于 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.
Contribution in any form is very welcome. Bugs, feature requests or feedback can be reported in form of Issues.
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.
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.
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:
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.
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.
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.
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.
Main component used as hub of behaviour tree.
Properties
Node Inspector - Inspector of node selected in Behaviour Tree editor window.
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.
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.
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.
[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; }
// }
}Entry node of behaviour tree.
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.
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.
Checks if blackboard variable is set. Node supports Bollean, Object and Transform variables. Selecting Invert option will produce "If not set" effect.
Checks if blackboard number variable meets requirement. Node supports Float and Int variables.
Checks distance between two transforms and returns success when given distance condition is met.
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.
Forces success or failure.
Inverts node result. Failure becomes Success and vice versa.
Triggers Unity Event with one parameter of selected type
There is fixed chance that node will be executed. Returns Failure if roll is not favorable.
Generates random float in provided range.
Generates random integer in provided range.
Repeats branch as long as Success is returned from the child. Use Loop node to create a more advanced flow.
Repeats branch specified amount of times or infinitely. Use Loop node to create a more advanced flow.
Repeats branch specified amount of times, infinitely or until selected result is returned. Results and flow can be fully customized.
Sets blackboard bool variable
Sets blackboard int or float variable
Sets blackb
暂无开放 Issues,或尚未同步最近议题。