Salomonsson.se
Apr 24 2017

Behavior Trees in Unity

How do you create a nice user (developer) friendly Behavior Tree in Unity? The hardest part with BT's is not making them, it is maintaining them! As they scale they become pretty hard to grasp, and you need good visual tools to debug. But I just got an idea that I want to write down somewhere before I go to sleep and forget all about it.

Introduction to BT's, if you don't know them: http://guineashots.com/2014/07/25/an-introduction-to-behavior-trees-part-1/

Interesting project with viusal editor (though way to buggy to be used, and also I don't like the performance warning in the readme): https://github.com/rev087/hivemind

Here is a rundown on how to create a similar visual editor, using Scriptable Objects: http://davidlegare.ghost.io/behavior-trees-1/

And lastly, you might have to read up on ScriptableObject as well: https://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/scriptable-objects

The idea

So, ScriptableObject has some problems for our usecase: It does not support polymorphism. So here is the idea on how to solve it.

  1. A BehaviorTree class, with custom PropertyDrawer
  2. All the basic nodes are built-in into BehaviorTree, such as Sequence, Parallel, Repeater and so on
  3. Custom Condition and Action nodes are added as MonoBehaviours to the gameObject (and thereby serialized with all their properties), but added by reference as a nodes in the BehaviorTree

It's not a pretty solution, but to me it beats most of the other solutions I have seen. Then it's just a matter of building that custom inspector for the BT.