Create a Behavior Tree from Script

In some circumstances you might want to create a behavior tree from script instead of directly relying on a prefab to contain the behavior tree for you. For example, you may have saved out an external behavior tree and want to load that tree in from a newly created behavior tree. This is possible by setting the externalBehavior variable on the behavior tree component:

using UnityEngine;
using BehaviorDesigner.Runtime;

public class CreateTree : MonoBehaviour
	public ExternalBehaviorTree behaviorTree;

	private void Start()
		var bt = gameObject.AddComponent<BehaviorTree>();
		bt.StartWhenEnabled = false;
		bt.ExternalBehavior = behaviorTree;

In this example the public variable behaviorTree contains a reference to your external behavior tree. When the newly created tree loads it will load the external behavior tree for all of its tasks. To prevent the tree from running immediately we set StartWhenEnabled to false. The tree can then be started manually with bt.EnableBehavior().