Implementing behavior trees
Behavior trees can be seen as a synthesis of a number of other artificial intelligence techniques, such as finite-state machines, planning, and decision trees. In fact, they share some resemblance to FSMs, but instead of states, we think in terms of actions spanned across a tree structure.
Getting ready
This recipe requires us to understand coroutines.
How to do it...
Just like decisions trees, we will create three pseudo-abstract classes for handling the process:
- First, let's create the
Task
base class, as shown in the following code:
using UnityEngine; using System.Collections; using System.Collections.Generic; public class Task : MonoBehaviour {
public List<Task> children; protected bool result = false; protected bool isFinished = false; }
- Next, we're going to implement the finalization function, as shown in the following code:
public virtual void SetResult(bool r) { result = r; isFinished = true; }
- We then implement the function...