# Behavior Designer - Opsive Documentation

> Complete Behavior Designer documentation, generated from the Opsive documentation source on 2026-08-07.

Documentation home: https://opsive.com/support/documentation/behavior-designer/

## Contents

- [Behavior Designer](#page-behavior-designer)
  - [Overview](#page-behavior-designer-overview)
  - [What is a Behavior Tree?](#page-behavior-designer-what-is-a-behavior-tree)
    - [Behavior Tree Flow](#page-behavior-designer-what-is-a-behavior-tree-behavior-tree-flow)
  - [Behavior Trees or Finite State Machines](#page-behavior-designer-behavior-trees-or-finite-state-machines)
  - [Installation](#page-behavior-designer-installation)
  - [Behavior Tree Component](#page-behavior-designer-behavior-tree-component)
    - [Create a Behavior Tree from Script](#page-behavior-designer-behavior-tree-component-create-a-behavior-tree-from-script)
  - [Behavior Manager](#page-behavior-designer-behavior-manager)
  - [Tasks](#page-behavior-designer-tasks)
  - [Parent Tasks](#page-behavior-designer-parent-tasks)
  - [Writing a New Conditional Task](#page-behavior-designer-writing-a-new-conditional-task)
  - [Writing a New Action Task](#page-behavior-designer-writing-a-new-action-task)
  - [Debugging](#page-behavior-designer-debugging)
  - [Variables](#page-behavior-designer-variables)
    - [Dynamic Variables](#page-behavior-designer-variables-dynamic-variables)
    - [Global Variables](#page-behavior-designer-variables-global-variables)
    - [Creating Shared Variables](#page-behavior-designer-variables-creating-shared-variables)
    - [Accessing Variables from non-Task Objects](#page-behavior-designer-variables-accessing-variables-from-non-task-objects)
  - [Conditional Aborts](#page-behavior-designer-conditional-aborts)
  - [Events](#page-behavior-designer-events)
  - [External Behavior Trees](#page-behavior-designer-external-behavior-trees)
  - [Networking](#page-behavior-designer-networking)
  - [Referencing Tasks](#page-behavior-designer-referencing-tasks)
  - [Object Drawers](#page-behavior-designer-object-drawers)
  - [Variable Synchronizer](#page-behavior-designer-variable-synchronizer)
  - [Syncing Animations](#page-behavior-designer-syncing-animations)
  - [Referencing Scene Objects](#page-behavior-designer-referencing-scene-objects)
  - [Task Attributes](#page-behavior-designer-task-attributes)
  - [Integrations](#page-behavior-designer-integrations)
    - [Dialogue System](#page-behavior-designer-integrations-dialogue-system-for-unity)
    - [Opsive Character Controllers](#page-behavior-designer-integrations-opsive-character-controllers)
    - [Playmaker](#page-behavior-designer-integrations-playmaker)
    - [uScript](#page-behavior-designer-integrations-uscript)
    - [Visual Scripting](#page-behavior-designer-integrations-visual-scripting)
  - [Videos](#page-behavior-designer-videos)

---

<a id="page-behavior-designer"></a>

# Behavior Designer

[View this page online](https://opsive.com/support/documentation/behavior-designer/)

---

<a id="page-behavior-designer-overview"></a>

# Overview

[View this page online](https://opsive.com/support/documentation/behavior-designer/overview/)

Behavior Designer is a behavior tree implementation designed for everyone - programmers, artists, designers. Behavior Designer offers a powerful API allowing you to easily create new tasks. it offers an intuitive visual editor with extensive third party integration making it possible to create complex AIs without having to write a single line of code. This guide is going to give a general overview of all aspects of Behavior Designer. If you're just getting started with behavior trees we have a "Behavior Tree Basics" [video series](https://www.youtube.com/watch?v=PuLuwzgYB4g&index=1&list=PLCPL5IYZm1NLVVxJx3-CFTLuHvLbCgmzk). This page also has a quick [overview](https://opsive.com/support/documentation/behavior-designer/what-is-a-behavior-tree/) of behavior trees. With Behavior Designer you don't need to know the underlying behavior tree implementation but is a good idea to know some of the key concepts such as the types of tasks (action, composite, conditional and decorator). When you first open Behavior Designer you'll see the following window:

![](https://opsive.com/wp-content/uploads/2018/03/BehaviorDesignerWindow-1024x594.png)

There are four sections within Behavior Designer. From the screenshot below, section 1 is the graph area. It is where you'll be creating the behavior trees. Section 2 is a properties panel. The properties panel is where you'll be editing the specific properties of a behavior tree, adding new tasks, creating new variables, or editing the parameters of a task. Section 3 is the behavior tree operations toolbar. You can use the drop down boxes to select existing behavior trees or add/remove behavior trees. The final section, section 4, is the debug toolbar. You can start/stop, step, and pause Unity within this panel. In addition, you'll see the number of errors that your tree has even before you start executing your tree.

![](https://opsive.com/wp-content/uploads/2018/03/BehaviorDesignerWindowSections-1024x594.png)

Section 1 is the main part of Behavior Designer that you'll be working in. Within this section you can create new tasks and arrange those tasks into a behavior tree. To start things off, you first need to add a Behavior Tree component. The Behavior Tree component will act as the manager of the behavior tree that you are just starting to create. You can create a new Behavior Tree component by right clicking within the graph area and clicking "Add Behavior Tree" or by clicking on the plus button next to "Lock" within the operations area of section 3. Once a Behavior Tree has been added you can start adding tasks. Add a task by right clicking within the graph area or clicking on the "Tasks" tab within section 2, the properties panel. New tasks can also be added by pressing the space bar and opening the quick task search window:

![](https://opsive.com/wp-content/uploads/2018/03/QuickTaskSearch.png)

Once a task has been added you'll see the following:

![](https://opsive.com/wp-content/uploads/2018/03/Sequence.png)

  In addition to the task that you added, the entry task also gets added. The entry task acts as the root of the tree. That is the only purpose of the entry task. The sequence task has an error because it has no children. As soon as you add a child the error will go away. Now that we've added our first task lets add a few more:

![](https://opsive.com/wp-content/uploads/2018/03/OverviewMoreTasks.png)

You can connect the sequence and selector task by dragging from the bottom of the sequence task to the top of the selector task. Repeat this process for the rest of the tasks. If you make a mistake you can selection a connection and delete it with the delete key. You can also rearrange the tasks by clicking on a task and dragging it around. Behavior Designer will execute the tasks in a depth first order. You can change the execution order of the tasks by dragging them to the left/right of their sibling. From the screenshot above, the tasks will be executed in the following order: SequenceA, SelectorA, SequenceB, ActionA, ActionB, ActionC, SelectorB, ActionD, ActionE

![](https://opsive.com/wp-content/uploads/2018/03/BehaviorDesignerWindowTaskProperties.png)

Now that we have a basic behavior tree created, lets modify the parameters on one of the tasks. Select the ActionC node to bring up the Inspector within the properties panel. You can see here that we can rename the task, set the task to be instant, or enter a task comment. In addition, we can modify all public variables the task class contains. This includes assigning variables created within Behavior Designer. In our case the only public variable is the _Rotation Speed._ The value that we set the parameter to will be used within the behavior tree. There are three other tabs within the properties panel: Variables, Tasks, and Behavior. The variables panel allows you to create variables that are shared between tasks. For more information take a look at the [variables topic](https://opsive.com/support/documentation/behavior-designer/variables/). The tasks panel lists all of the possible tasks that you can use. This is the same list as what is found when you right click and add a task. This list is created by searching for any class that is derived from the action, composite, conditional, or decorator task type. The last panel, the behavior panel, shows the inspector for the Behavior Tree component that you added when you first created a behavior tree. More details on what each option does is on the [Behavior Component Overview page](https://opsive.com/support/documentation/behavior-designer/behavior-tree-component/).

![](https://opsive.com/wp-content/uploads/2018/03/BehaviorDesignerToolbarOperations.png)

The final section within the Behavior Designer window is the operations toolbar. The operations toolbar is mostly used for selecting behavior trees as well as adding/removing behavior trees. The following operations are labeled:

-   Label 1: Navigate back/forward between the behavior trees that you have opened.
-   Label 2: Lists all of the behavior trees that are within the scene or project (includes prefabs).
-   Label 3: Lists any GameObject within the scene that has the behavior tree component added to it.
-   Label 4: Lists any behavior tree that are attached to the GameObject that is selected from label 3.
-   Label 5: Lists any external behavior trees that the current behavior tree references
-   Label 6: Removes the currently selected behavior tree.
-   Label 7: Adds a new behavior tree to the GameObject.
-   Label 8: Keeps the current behavior tree active even if you have selected a different GameObject within the hierarchy or project window
-   Label 9: Exports the behavior tree to an external behavior tree asset.
-   Label 10: Opens the find dialogue which can search your behavior tree.
-   Label 11: Takes a screenshot of the current behavior tree.
-   Label 12: Shows the Behavior Designer preferences.

New tasks can be added with three different methods:

-   The task inspector within the left panel.
-   Right click within the graph.
-   Press the spacebar in the graph to show a quick task search.

---

<a id="page-behavior-designer-what-is-a-behavior-tree"></a>

# What is a Behavior Tree?

[View this page online](https://opsive.com/support/documentation/behavior-designer/what-is-a-behavior-tree/)

Behavior trees are a popular AI technique used in many games. Halo 2 was the first mainstream game to use behavior trees and they started to become more popular after a [detailed description](http://www.gamasutra.com/view/feature/130663/gdc_2005_proceeding_handling_.php) of how they were used in Halo 2 was released. Behavior trees are a combination of many different AI techniques: hierarchical state machines, scheduling, planning, and action execution. One of their main advantages is that they are easy to understand and can be created using a visual editor. Some would even say that they are the cornerstone of modern AI: https://www.youtube.com/watch?v=6VBCXvfNlCM At the simplest level behavior trees are a collection of tasks. There are four different types of tasks: action, conditional, composite, and decorator. Action tasks are probably the easiest to understand in that they alter the state of the game in some way. Conditional tasks test some property of the game. For example, in the tree below the AI agent has two conditional tasks and two action tasks. The first two conditional tasks check to see if there is an enemy within sight of the agent and then ensures the agent has enough bullets to fire his weapon. If both of these conditions are true then the two action tasks will run. One of the action tasks shoots the weapon and the other task plays a shooting animation. The real power of behavior trees comes into play when you form different sub-trees. The two shooting actions could form one sub-tree. If one of the earlier conditional tasks fails then another sub-tree could be made that plays a different set of action tasks such as running away from the enemy. You can group sub-trees on top of each other to form a high level behavior.

![](https://opsive.com/wp-content/uploads/2018/03/BehaviorTreeExample.png)

Composite tasks are a parent task that hold a list of child tasks. From the above example, the composite tasks are labeled sequence and parallel. A sequence task runs each task once until all tasks have been run. It first runs the conditional task that checks to see if an enemy is within sight. If an enemy is within sight then it will run the conditional task that checks to see if the agent has any bullets left. If the agent has enough bullets then the parallel task will run that shoots the weapon and plays the shooting animation. Where a sequence task executes one child task at a time, a parallel task executes all of its children at the same time. The final type of task is the decorator task. The decorator task is a parent task that can only have one child. Its function is to modify the behavior of the child task in some way. In the above example we didn't use a decorator task but you may want to use one if you want to stop a task from running prematurely (called the interrupt task). For example, an agent could be performing a task such as collecting resources. It could then have an interrupt task that will stop the collection of resources if an enemy is nearby. Another example of a decorator task is one that reruns its child task x number of times or a decorator task that keeps running the child task until it completes successfully. One of the major behavior tree topics that we have left out so far is the return status of a task. You may have a task that takes more than one frame to complete. For example, most animations aren't going to start and finish within just one frame. In addition, conditional tasks need a way to tell their parent task whether or not the condition was true so the parent task can decide if it should keep running its children. Both of these problems can be solved using a task status. A task is in one of three different states: running, success, or failure. In the first example the shoot animation task has a task status of running for as long as the shoot animation is playing. The conditional task of determining if an enemy is within sight will return success or failure within one frame. Behavior Designer takes all of these concepts and packages it up in an easy to use interface with an API that is similar to Unity's MonoBehaviour API. Behavior Designer includes many composite and decorator classes within the standard installation. Action and conditional tasks are more game specific so not as many of those tasks are included but there are many examples within the [sample projects](/integrations/?pid=803). New tasks can be created by [extending from](https://opsive.com/support/documentation/behavior-designer/writing-a-new-conditional-task/) one of the task types. In addition, many [videos](https://opsive.com/support/documentation/behavior-designer/videos/) have been created to make learning Behavior Designer as easy as possible. When you are just getting started it is recommended that you start with [this tutoria](https://opsive.com/support/documentation/behavior-designer/what-is-a-behavior-tree/behavior-tree-flow/)l. From here you'll be able to apply the same building blocks to create a much more advanced AI logic.

---

<a id="page-behavior-designer-what-is-a-behavior-tree-behavior-tree-flow"></a>

# Behavior Tree Flow

[View this page online](https://opsive.com/support/documentation/behavior-designer/what-is-a-behavior-tree/behavior-tree-flow/)

Now that you have an understanding of what a behavior tree is, lets take a look at a specific example. For this example we are going to follow the same setup as the video below: https://www.youtube.com/watch?v=PuLuwzgYB4g&list=PLCPL5IYZm1NLVVxJx3-CFTLuHvLbCgmzk To get started download the tutorial assets from [this link](https://opsive.com/wp-content/uploads/2019/11/BehaviorDesignerTutorials.unitypackage). Open the Behavior Tree scene and notice there is a Behavior Tree added to the Agent GameObject. Duplicate the Agent GameObject and disable the original GameObject. You should then remove the Behavior Tree component so we can start fresh. Rename the duplicated GameObject to "New Agent". Your hierarchy should now look like:

![](https://opsive.com/wp-content/uploads/2024/08/BehaviorTreeFlowNewAgent.png)

On the New Agent GameObject add the Behavior Tree component. Lets start with a basic behavior tree that moves the agent to the enemy after a short delay. In order to do this add the Sequence task, followed by the Wait and Seek tasks. Connect the Sequence task to the Entry task and the Wait and Seek tasks to the Sequence task. The Wait task should be to the left of the Seek task:

![](https://opsive.com/wp-content/uploads/2024/08/BehaviorTreeFlowSimpleSeek.png)

In behavior tree jargon a Sequence task is similar to an "AND" in the programming world. Behavior trees execute from top to bottom, left to right. Since the Sequence task is connected to Entry the Sequence task will run first. The Sequence task will determine which child it should run, and since it moves from left to right the first task it selects is the Wait task. After Wait has completed the next task that will run is Seek. Once Seek has run there are no more tasks so the behavior tree will end. Lets see this in action. Before you hit play in the Unity editor first increase the _Arrived Distance_ and then specify the _Target_ that the Seek task should move to.

![](https://opsive.com/wp-content/uploads/2024/08/BehaviorTreeFlowSimpleSeekInspector.png)

Now select play in Unity. You'll see the agent move towards the enemy after the wait time. When the Seek task is within the _Arrive Distance_ the task will complete successfully. And with that, you created your first behavior tree! With the basics down lets now create a little more complicated behavior tree. We now want to have the agent seek the target after the target is within sight instead of seeking after a delay. In order to accomplish this we are going to add a few new types of tasks. Create a new behavior tree and add the following tasks: Selector, Sequence, Can See Object, Seek, and Idle. Arrange and connect the tasks so you get the following:

![](https://opsive.com/wp-content/uploads/2024/08/BehaviorTreeFlowCanSee.png)

Lets complete the setup before by setting the Can See Object _Target Object_ variable to the enemy:

![](https://opsive.com/wp-content/uploads/2024/08/BehaviorTreeFlowCanSeeObjectInspector.png)

And then set the same variables on the Seek task as before:

![](https://opsive.com/wp-content/uploads/2024/08/BehaviorTreeFlowSimpleSeekInspector.png)

With this tree we have a few new concepts. The first concept is the Selector task. If the Sequence task is similar to an "AND" then the Selector is similar to an "OR". After the tasks execute they will return a status:

-   _Running_: The task should continue to execute.
-   _Failure_: The task failed.
-   _Success_: The task succeeded.

The Selector task will select child tasks from left to right until a child returns a status of success. When this behavior tree starts the Selector task will run the Sequence task, which will then run Can See Object. Since the agent cannot see the target initially the Can See Object task will return a Failure status. When a child of the Sequence task returns failure the Sequence task will also return Failure. The next task that runs is the Selector task again which sees that it has a child that returned Failure so it needs to move onto the next child. Idle is next and the Idle task always returns a status of Running. Go ahead and hit play so you can see this in action:

![](https://opsive.com/wp-content/uploads/2024/08/BehaviorTreeFlowCanSeeInitialStatus.png)

If Idle always returns a status of Running, how do we stop it from executing? There are a couple of different ways, but the easiest method is to use a concept called [Conditional Aborts](https://opsive.com/support/documentation/behavior-designer/conditional-aborts/). After you complete this tutorial you'll want to go through the Conditional Aborts page/video, but as an overview conditional aborts will reevaluate conditional tasks while other tasks are active. For this tree we are going to set a _Lower Priority_ conditional abort on the Sequence task:

![](https://opsive.com/wp-content/uploads/2024/08/BehaviorTreeFlowCanSeeLowerPrioritySequence.png)

The _Lower Priority_ abort type will reevaluate the child conditional tasks when a branch to the right of the task is active. In this case, since the Idle task has a lower priority than the Sequence task (remember behavior trees execute from left to right, so because Idle is to the right of Sequence it has a lower priority) the Can See Object task will reevaluate. When you hit play you should the Can See Object task has a failure return status icon but that icon also has a loop around it indicating that it is being reevaluated:

![](https://opsive.com/wp-content/uploads/2024/08/BehaviorTreeFlowCanSeeObjectReevaluate.png)

Since Can See Object is now being reevaluated when the enemy comes within sight of the agent you'll see the Can See Object status switch from Failure to Success. The Seek task will now run allowing the agent to reach the enemy.

![](https://opsive.com/wp-content/uploads/2024/08/BehaviorTreeFlowCanSeeObjectSeeking.png)

With this you now have the building blocks to create a much more advanced behavior tree. The links below contain explanation for some more advanced behavior tree setups:

-   [Opsive Character Controller Integration Explanation](https://opsive.com/support/documentation/behavior-designer/integrations/opsive-character-controllers/)
-   [Deathmatch AI Kit Implementation Explanation](https://opsive.com/support/documentation/deathmatch-ai-kit/behavior-tree-overview/)
-   [Awesome AI made Easy with Behavior Designer](https://thestrangeschool.vhx.tv/checkout/easy-awesome-ai-with-behavior-designer/purchase)
-   [Unity AI Guide: Create a Autonomous Game with Adaptive NPCs](https://www.udemy.com/course/unity-ai-guide-create-a-autonomous-game-with-adaptive-npcs/?referralCode=895A0356AC20743582B5)
-   [Recreating the FALSE KNIGHT Boss Fight](https://www.youtube.com/watch?v=X7VwAGvAOIw)
-   [Practical Guide to AI in Unity](https://www.udemy.com/course/ai-in-unity/)

---

<a id="page-behavior-designer-behavior-trees-or-finite-state-machines"></a>

# Behavior Trees or Finite State Machines

[View this page online](https://opsive.com/support/documentation/behavior-designer/behavior-trees-or-finite-state-machines/)

Behavior Trees and Finite State Machines (FSMs) are widely used techniques for organizing complex gameplay and AI logic. Although both can be used to model behavior, they are built around different core responsibilities and excel at different layers of system design.

Behavior Trees are optimized for decision-making systems that must react dynamically to changing conditions, prioritize actions, and handle complex branching logic. Finite State Machines are optimized for state-driven control systems that manage stable modes of operation, enforce structured flow, and define explicit transitions between behaviors.

In practice, these paradigms are rarely exclusive. Well-architected systems often combine decision-making logic with state-based control, creating clear separation between choosing actions and executing them.

#### Decision-Making vs State Control

At a high level, these approaches address two separate concerns:

-   Decision-making: Determining what should happen next.
-   _State control:_ Managing which mode or phase is currently active.

Understanding this distinction helps clarify when each approach is most effective.

#### Behavior Trees : Decision-Making Systems

![](https://opsive.com/wp-content/uploads/2024/12/WhatIsABehaviorTreeStructure.png)

Behavior trees are designed around evaluating conditions and selecting actions. They continuously assess the game state and determine the most appropriate behavior to execute. They are particularly strong at:

-   High-level decision-making.
-   Priority-based behavior selection.
-   Reactive logic that adapts to changing conditions.
-   Managing complex branching choices.

#### Finite State Machines : State-Based Control Systems

![https://d3kjluh73b9h9o.cloudfront.net/original/4X/3/5/a/35ae306bb64982748fa23cc7ba5a8f1254f872ac.png](https://d3kjluh73b9h9o.cloudfront.net/original/4X/3/5/a/35ae306bb64982748fa23cc7ba5a8f1254f872ac.png)

Finite state machines focus on managing discrete states and transitions between them. Each state represents a distinct mode of operation, and transitions define how and when the system moves between modes. They are particularly strong at:

-   Controlling execution flow.
-   Managing stable modes or phases.
-   Enforcing structured sequences.
-   Handling predictable behavior cycles.

#### Core Differences

| Decision-Making (Behavior Trees) | State Control (FSMs) |
| --- | --- |
| Select what action to perform | Control current mode or phase |
| Continuously evaluate conditions | Transition between explicit states |
| Dynamic and reactive | Structured and predictable |
| Handle complex branching logic | Handle flow and sequencing |
| Scale well for decision complexity | Can become complex as states grow |

#### When to use a Decision-Making System

Use a Behavior Tree when:

-   Multiple actions are possible at any time.
-   Logic depends on changing conditions.
-   Priority and fallback behaviors are required.
-   Systems must adapt in real time.

Typical examples include AI behavior selection and complex gameplay logic.

#### When to use a State Control System

Use a FSM when:

-   Behavior is organized into distinct modes.
-   Flow follows predictable transitions.
-   Entry and exit logic must be explicit.
-   Sequenced behavior is important.

Common examples include animation states, gameplay phases, and mode-based systems.

#### Using Both Together

In many projects, decision-making and state control are used together:

-   A decision-making system determines which state should be active.
-   A state control system manages what happens within that state.

This layered approach keeps logic clear, scalable, and easier to maintain

---

<a id="page-behavior-designer-installation"></a>

# Installation

[View this page online](https://opsive.com/support/documentation/behavior-designer/installation/)

After Behavior Designer is imported you can access it from the Tools toolbar. You can access the runtime source code by importing the Runtime Source Code package located [here](/downloads/?pid=803) on the Downloads page. **Before you extract this package ensure that you have deleted the /Assets/BehaviorDesigner folder otherwise you'll get a compile error.** In order to compile Behavior Designer for the Universal Windows Platform (UWP) you must use the runtime source code instead of the compiled DLL. No compile settings need to be changed - Behavior Designer can compile with .Net Core enabled. When you try to run your UWP app you may get an error indicating that the tasks cannot be found. In order to fix this the following line within TaskUtility.GetTypesWithinAssembly (within TaskUtility.cs) should be changed from:

```csharp
loadedAssemblies = GetStorageFileAssemblies(typeName).Result;
```

to:

```csharp
loadedAssemblies = new List();
loadedAssemblies.Add("Assembly-CSharp");
```

This will allow Unity's C# assembly to be found within the app. If using IL2CPP to build your project you may receive a MissingMethodException related to the Default Constructor not being found. This can be fixed by doing one of the following:

-   Import the runtime source package.
-   Change the stripping level to Low.
-   Add the missing class to a [link.xml](https://docs.unity3d.com/Manual/ManagedCodeStripping.html) file.

---

<a id="page-behavior-designer-behavior-tree-component"></a>

# Behavior Tree Component

[View this page online](https://opsive.com/support/documentation/behavior-designer/behavior-tree-component/)

![](https://opsive.com/wp-content/uploads/2018/03/BehaviorTreeComponent.png)

The behavior tree component stores your behavior tree and acts as the interface between Behavior Designer and the tasks. The following API is exposed for starting and stopping your behavior tree:

```csharp
public void EnableBehavior();
// pause:  temporarily stop the behavior tree at its current execution point. It can be resumed with EnableBehavior.
public void DisableBehavior(bool pause = false);
```

You can find tasks using one of the following methods:

```csharp
TaskType FindTask<TaskType>();
List<TaskType> FindTasks<TaskType>();
Task FindTaskWithName(string taskName);
List<Task> FindTasksWithName(string taskName);
```

The current execution status of the tree can be obtained by calling:

```csharp
behaviorTree.ExecutionStatus
```

A status of Running will be returned when the tree is running. When the tree finishes the execution status will be Success or Failure depending on the task results. The following events can also be subscribed to:

```csharp
OnBehaviorStart
OnBehaviorRestart
OnBehaviorEnd
```

The behavior tree component has the following properties:

###### Behavior Name

The name of the behavior tree.

###### Behavior Description

Describes what the behavior tree does.

###### External Behavior

A field to specify the external behavior tree that should be run when this behavior tree starts.

###### Group

A numerical grouping of behavior trees. Can be used to easily find behavior trees. The CTF sample project shows an example of this.

###### Start When Enabled

If true, the behavior tree will start running when the component is enabled.

###### Asynchronous Load

Specifies if the behavior tree should load in a separate thread. Because Unity does not allow for API calls to be made on worker threads this option should be disabled if you are using property mappings for the [shared variables](https://opsive.com/support/documentation/behavior-designer/variables/).

###### Pause When Disabled

If true, the behavior tree will pause when the component is disabled. If false, the behavior tree will end.

###### Restart When Complete

If true, the behavior tree will restart from the beginning when it has completed execution. If false, the behavior tree will end.

###### Reset Values On Restart

If true, the variables and task public variables will be reset to their original values when the tree restarts.

###### Log Task Changes

Used for debugging. If enabled, the behavior tree will output any time a task status changes, such as it starting or stopping.

---

<a id="page-behavior-designer-behavior-tree-component-create-a-behavior-tree-from-script"></a>

# Create a Behavior Tree from Script

[View this page online](https://opsive.com/support/documentation/behavior-designer/behavior-tree-component/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](https://opsive.com/support/documentation/behavior-designer/external-behavior-trees/) 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:

```csharp
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().

---

<a id="page-behavior-designer-behavior-manager"></a>

# Behavior Manager

[View this page online](https://opsive.com/support/documentation/behavior-designer/behavior-manager/)

![](https://opsive.com/wp-content/uploads/2018/03/BehaviorManager.png)

When a behavior tree runs it creates a new GameObject with a Behavior Manager component if it isn't already created. This component manages the execution of all of the behavior trees in your scene. You can control how often the behavior trees tick by changing the update interval property. "Every Frame" will tick the behavior trees every frame within the Update loop. "Specify Seconds" allows you to tick the behavior trees a given number of seconds. The final option is "Manual" which will give you the control of when to tick the behavior trees. You can tick the behavior trees by calling tick:

```csharp
BehaviorManager.instance.Tick();
```

In addition, if you want each behavior tree to have its own tick rate you can tick each behavior tree manually with:

```csharp
BehaviorManager.instance.Tick(BehaviorTree)
```

Task Execution Type allows you to specify if the behavior tree should continue executing tasks until it hits an already executed task during that tick or if it should continue to execute the tasks until a maximum number of tasks have been executed during that tick. As an example, consider the following behavior tree:

![](https://opsive.com/wp-content/uploads/2018/03/TaskExecutionType.png)

The Repeater task is set to repeat 5 times. If the Task Execute Type is set to No Duplicates, the Play Sound task will only execute once during a single tick. If the Task Execution Type is set to Count, a maximum task execution count can be specified. If a value of 5 is specified then the Play Sound task will execute all 5 times in a single tick. If you want to persist your behavior trees across scenes you can mark the BehaviorManager as [DontDestroyOnLoad](https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html). Make sure you also mark your Behavior Tree component that you want to persist as DontDestroyOnLoad as well.

---

<a id="page-behavior-designer-tasks"></a>

# Tasks

[View this page online](https://opsive.com/support/documentation/behavior-designer/tasks/)

At the highest level a behavior tree is a collection of tasks. Tasks have a similar API to Unity's MonoBehaviour so it should be really easy to get started [writing your own tasks](https://opsive.com/support/documentation/behavior-designer/writing-a-new-conditional-task/). The task class has the following API:

```csharp
// OnAwake is called once when the behavior tree is enabled. Think of it as a constructor.
void OnAwake();

// OnStart is called immediately before execution. It is used to setup any variables that need to be reset from the previous run.
void OnStart();

// OnUpdate runs the actual task.
TaskStatus OnUpdate();

// OnFixedUpdate executes during the FixedUpdate loop. The TaskStatus must be returned within OnUpdate.
void OnFixedUpdate();

// OnEnd is called after execution on a success or failure.
void OnEnd();

// OnPause is called when the behavior is paused or resumed.
void OnPause(bool paused);

// Returns the priority of the task, used by the Priority Selector.
float GetPriority();

// Returns the utility of the task, used by the Utility Selector for Utility Theory.
float GetUtility();

// OnBehaviorComplete is called after the behavior tree finishes executing.
void OnBehaviorComplete();

// OnReset is called by the inspector to reset the public properties
void OnReset();

// Allow OnDrawGizmos to be called from the tasks.
void OnDrawGizmos();

// Keep a reference to the behavior that owns this task.
Behavior Owner;
```

Tasks have three exposed properties: name, comment, and instant. Instant is the only property that isn't obvious in what it does. When a task returns success or fail it immediately moves onto the next task within the same update tick. If you uncheck the instant task it will now wait a update tick before the next task gets executed. This is an easy way to throttle the behavior tree. The following flow chart is used when executing the task:

![](https://opsive.com/wp-content/uploads/2018/03/TaskFlowChart.png)

---

<a id="page-behavior-designer-parent-tasks"></a>

# Parent Tasks

[View this page online](https://opsive.com/support/documentation/behavior-designer/parent-tasks/)

Parent Tasks are the composite and decorator tasks within the behavior tree. While the ParentTask API has no equivalent API to Unity's MonoBehaviour class, it is still pretty easy to determine what each method is used for.

```csharp
// The maximum number of children a parent task can have. Will usually be 1 or int.MaxValue
public virtual int MaxChildren();

// Boolean value to determine if the current task is a parallel task.
public virtual bool CanRunParallelChildren();

// The index of the currently active child.
public virtual int CurrentChildIndex();

// Boolean value to determine if the current task can execute.
public virtual bool CanExecute();

// Apply a decorator to the executed status.
public virtual TaskStatus Decorate(TaskStatus status);

// Notifies the parent task that the child has been executed and has a status of childStatus.
public virtual void OnChildExecuted(TaskStatus childStatus);

// Notifies the parent task that the child at index childIndex has been executed and has a status of childStatus.
public virtual void OnChildExecuted(int childIndex, TaskStatus childStatus);

// Notifies the task that the child has started to run.
public virtual void OnChildStarted();

// Notifies the parallel task that the child at index childIndex has started to run.
public virtual void OnChildStarted(int childIndex);

// Some parent tasks need to be able to override the status, such as parallel tasks.
public virtual TaskStatus OverrideStatus(TaskStatus status);

// The interrupt node will override the status if it has been interrupted.
public virtual TaskStatus OverrideStatus();

// Notifies the composite task that an conditional abort has been triggered and the child index should reset.
public virtual void OnConditionalAbort(int childIndex);
```

---

<a id="page-behavior-designer-writing-a-new-conditional-task"></a>

# Writing a New Conditional Task

[View this page online](https://opsive.com/support/documentation/behavior-designer/writing-a-new-conditional-task/)

This topic is divided into two parts. The first part describes writing a new conditional task, and the second part ([available here](https://opsive.com/support/documentation/behavior-designer/writing-a-new-action-task/)) describes writing a new action task. The conditional task will determine if any objects are within sight and the action class will towards the object that is within sight. We will also be using [variables](https://opsive.com/support/documentation/behavior-designer/variables/) for both of these tasks. We have also recorded a video on this topic and it is available on [YouTube](https://www.youtube.com/watch?v=q58ELfkyjQk). The first task that we will write is the Within Sight task. Since this task will not be changing game state and is just checking the status of the game this task will be derived from the Conditional task. Make sure you have the BehaviorDesigner.Runtime.Tasks namespace included:

```csharp
using UnityEngine;
using BehaviorDesigner.Runtime.Tasks;

public class WithinSight : Conditional
{
}
```

We now need to create three public variables and one private variable:

```csharp
using UnityEngine;
using BehaviorDesigner.Runtime;
using BehaviorDesigner.Runtime.Tasks;

public class WithinSight : Conditional
{
   public float fieldOfViewAngle;
   public string targetTag;
   public SharedTransform target;

   private Transform[] possibleTargets;
}
```

The _field of view angle_ is the field of view that the object can see. _Target tag_ is the tag of the targets that the object can move towards. _Target_ is a [Shared Variable](https://opsive.com/support/documentation/behavior-designer/variables/) which will be used by both the Within Sight and the Move Towards tasks. If you are using Shared Variables make sure you include the BehaviorDesigner.Runtime namespace. The final variable, _possible targets_, is a cache of all of the Transforms with the _target tag_. If you take a look at the [task API](https://opsive.com/support/documentation/behavior-designer/tasks/), you can see that we can create that cache within the the OnAwake or OnStart method. Since the list of possible transforms are not going to be changing as the Within Sight task is enabled/disabled we are going to do the caching within OnAwake:

```csharp
   public override void OnAwake()
   {
      var targets = GameObject.FindGameObjectsWithTag(targetTag);
      possibleTargets = new Transform[targets.Length];
      for (int i = 0; i < targets.Length; ++i) {
         possibleTargets[i] = targets[i].transform;
      }
   }
```

This OnAwake method will find all of the GameObjects with the _target tag_, then loop through them caching their transform in the _possible targets_ array. The _possible targets_ array is then used by the overridden OnUpdate method:

```csharp
   public override TaskStatus OnUpdate()
   {
      for (int i = 0; i < possibleTargets.Length; ++i) {
         if (WithinSight(possibleTargets[i], fieldOfViewAngle)) {
            target.Value = possibleTargets[i];
            return TaskStatus.Success;
         }
      }
      return TaskStatus.Failure;
   }
```

Every time the task is updated it checks to see if any of the _possible targets_ are within sight. If one target is within sight it will set the target value and return success. Setting this target value is key as this allows the Move Towards task to know what direction to move in. If there are no targets within sight then the task will return failure. The last part of this task is the WithinSight method:

```csharp
   public bool WithinSight(Transform targetTransform, float fieldOfViewAngle)
   {
      Vector3 direction = targetTransform.position - transform.position;
      return Vector3.Angle(direction, transform.forward) < fieldOfViewAngle;
   }
```

This method first gets a direction vector between the current transform and the _target transform_. It will then compute the angle between the direction vector and the current forward vector to determine the angle. If that angle is less then _field of view angle_ then the _target transform_ is within sight of the current Transform. That's it for the Within Sight task. Here's what the full task looks like:

```csharp
using UnityEngine;
using BehaviorDesigner.Runtime;
using BehaviorDesigner.Runtime.Tasks;

public class WithinSight : Conditional
{
   // How wide of an angle the object can see
   public float fieldOfViewAngle;
   // The tag of the targets
   public string targetTag;
   // Set the target variable when a target has been found so the subsequent tasks know which object is the target
   public SharedTransform target;

   // A cache of all of the possible targets
   private Transform[] possibleTargets;

   public override void OnAwake()
   {
      // Cache all of the transforms that have a tag of targetTag
      var targets = GameObject.FindGameObjectsWithTag(targetTag);
      possibleTargets = new Transform[targets.Length];
      for (int i = 0; i < targets.Length; ++i) {
         possibleTargets[i] = targets[i].transform;
      }
   }

   public override TaskStatus OnUpdate()
   {
      // Return success if a target is within sight
      for (int i = 0; i < possibleTargets.Length; ++i) {
         if (WithinSight(possibleTargets[i], fieldOfViewAngle)) {
            // Set the target so other tasks will know which transform is within sight
            target.Value = possibleTargets[i];
            return TaskStatus.Success;
         }
      }
      return TaskStatus.Failure;
   }

   // Returns true if targetTransform is within sight of current transform
   public bool WithinSight(Transform targetTransform, float fieldOfViewAngle)
   {
      Vector3 direction = targetTransform.position - transform.position;
      // An object is within sight if the angle is less than field of view
      return Vector3.Angle(direction, transform.forward) < fieldOfViewAngle;
   }
}
```

Continue to the second part of this topic, [writing the Move Towards task](https://opsive.com/support/documentation/behavior-designer/writing-a-new-action-task/).

---

<a id="page-behavior-designer-writing-a-new-action-task"></a>

# Writing a New Action Task

[View this page online](https://opsive.com/support/documentation/behavior-designer/writing-a-new-action-task/)

This topic is a continuation of the previous topic. It is recommended that you first take a look at the [writing a new conditional task](https://opsive.com/support/documentation/behavior-designer/writing-a-new-conditional-task/) topic first. The next task that we are going to write is the Move Towards task. Since this task is going to be changing the game state (moving an object from one position to another), we will derive the task from the Action class:

```csharp
using UnityEngine;
using BehaviorDesigner.Runtime.Tasks;

public class MoveTowards : Action
{
}
```

This class will only need two variables: a way to set the speed and the transform of the object that we are targeting:

```csharp
using UnityEngine;
using BehaviorDesigner.Runtime;
using BehaviorDesigner.Runtime.Tasks;

public class MoveTowards : Action
{
   public float speed = 0;
   public SharedTransform target;
}
```

The _target_ variable is a SharedTransform and it will be set from the Within Sight task that will run just before the Move Towards task. To do the actual movement, we will need to override the OnUpdate method:

```csharp
   public override TaskStatus OnUpdate()
   {
      if (Vector3.SqrMagnitude(transform.position - target.Value.position) < 0.1f) {
         return TaskStatus.Success;
      }
      transform.position = Vector3.MoveTowards(transform.position, target.Value.position, speed * Time.deltaTime);
      return TaskStatus.Running;
   }
```

When the OnUpdate method is run, it will check to see if the object has reached the _target_. If the object has reached the _target_ then the task will success. If the _target_ has not been reached yet the object will move towards the _target_ at a speed specified by the _speed_ variable. Since the object hasn't reached the target yet the task will return running. That's the entire Move Towards task. The full task looks like:

```csharp
using UnityEngine;
using BehaviorDesigner.Runtime;
using BehaviorDesigner.Runtime.Tasks;

public class MoveTowards : Action
{
   // The speed of the object
   public float speed = 0;
   // The transform that the object is moving towards
   public SharedTransform target;

   public override TaskStatus OnUpdate()
   {
      // Return a task status of success once we've reached the target
      if (Vector3.SqrMagnitude(transform.position - target.Value.position) < 0.1f) {
         return TaskStatus.Success;
      }
      // We haven't reached the target yet so keep moving towards it
      transform.position = Vector3.MoveTowards(transform.position, target.Value.position, speed * Time.deltaTime);
      return TaskStatus.Running;
   }
}
```

Now that these two tasks are written, parent the tasks by a sequence task and set the variables within the task inspector. Make sure you've also created a new variable within Behavior Designer:

![](https://opsive.com/wp-content/uploads/2018/03/WritingANewTask.png)

That's it! Create a few moving GameObjects within the scene assigned with the same tag as targetTag. When the game starts the object with the behavior tree attached with move towards whatever object first appears within its field of view. This was a pretty basic example and the tasks can get a lot more complicated depending on what you want them to do. All of the tasks within the sample projects are well commented so you should be able to pick it up from there. In addition, we have written some more documentation on the continuing topics such as [variables](https://opsive.com/support/documentation/behavior-designer/variables/), [referencing tasks](https://opsive.com/support/documentation/behavior-designer/referencing-tasks/) and [task attributes](https://opsive.com/support/documentation/behavior-designer/task-attributes/).

---

<a id="page-behavior-designer-debugging"></a>

# Debugging

[View this page online](https://opsive.com/support/documentation/behavior-designer/debugging/)

![](https://opsive.com/wp-content/uploads/2018/03/DebuggingOverview.png)

When a behavior tree is running you will see different tasks change colors between gray and green. When the task is green that means it is currently executing. When the task is gray it is not executing. After the task has executed it will have a check or x on the bottom right corner. If the task returned success then a check will be displayed. If it returned failure then an x will be displayed. While tasks are executing you can still change the values within the inspector and that change will be reflected in game.

![](https://opsive.com/wp-content/uploads/2018/03/Breakpoint.png)

Right clicking on a task will bring up a menu which allows you to set a breakpoint. If a breakpoint is set on a particular task then Behavior Designer will pause Unity whenever that task is activated. This is useful if you want to see when a particular task is executed.

![](https://opsive.com/wp-content/uploads/2018/03/WatchedVariables.png)

When a task is selected you have the option of watching a variable within the graph by clicking on the magnifying glass to the left of the variable name. Watched variables are a good way to see the value of a particular variable without having to have the task inspector open. In the example above the variables "Fleed Distance" and "Flee From Transform" are being watched and appear to the right of the Flee task.

![](https://opsive.com/wp-content/uploads/2018/03/DisabledTasks.png)

Sometimes you only want to focus on a certain set of tasks and prevent the rest from running. This is possible by disabling a set of tasks. Tasks can be disabled by hovering over the task and selecting the orange X on the top left of the task. Disabled tasks will not run and return success immediately. Disabled tasks appear in a darker color than the enabled tasks within the graph.

![](https://opsive.com/wp-content/uploads/2018/03/BehaviorDebugging.png)

One more debugging option is to output to the console any time a task changes state. If _Log Task Changes_ is enabled then you'll see output to the log similar to the following:

```csharp
GameObject - Behavior: Push task Sequence (index 0) at stack index 0
GameObject - Behavior: Push task Wait (index 1) at stack index 0
GameObject - Behavior: Pop task Wait (index 1) at stack index 0 with status Success
GameObject - Behavior: Push task Wait (index 2) at stack index 0
GameObject - Behavior: Pop task Wait (index 2) at stack index 0 with status Success
GameObject - Behavior: Pop task Sequence (index 0) at stack index 0 with status Success
Disabling GameObject - Behavior
```

These messages can be broken up into the following pieces:

```csharp
{game object name } - {behavior name}: {task change} {task type} (index {task index}) at stack index {stack index} {optional status}
```

{game object name} is the name of the game object that the behavior tree is attached to. {behavior name} is the name of the behavior tree. {task change} indicates the new status of the task. For example, a task will be pushed onto the stack when it starts executing and it will be popped when it is done executing . {task type} is the class type of the task. {task index} is the index of the task in a depth first search. {stack index} is the index of the stack that the task is being pushed to. If you have a parallel node then you'll be using multiple stacks. {optional status} is any extra status for that particular change. The pop task will output the task status.

---

<a id="page-behavior-designer-variables"></a>

# Variables

[View this page online](https://opsive.com/support/documentation/behavior-designer/variables/)

One of the advantages of behavior trees are that they are very flexible in that all of the tasks are loosely coupled - meaning one task doesn't depend on another task to operate. The drawback of this is that sometimes you need tasks to share information with each other. For example, you may have one task that is determine if a target is Within Sight. If the target is within sight you might have another task Move Towards the target. In this case the two tasks need to communicate with each other so the Move Towards task actually moves in the direction of the same object that the Within Sight task found. In traditional behavior tree implementations this is solved by coding a blackboard. With Behavior Designer it is a lot easier in that you can use variables. In our previous example we had two tasks: one that determined if the target is within sight and then the other task moves towards the target. This tree looks like:  

![](https://opsive.com/wp-content/uploads/2018/03/VariableTree.png)

The code for both of these tasks is discussed in the [Writing a New Task](https://opsive.com/support/documentation/behavior-designer/writing-a-new-conditional-task/) topic, but the part that deals with variables is in this variable declaration:

```csharp
public SharedTransform target;
```

With the SharedTransform variable created, we can now create a new variable within Behavior Designer and assign that variable to the two tasks:

![](https://opsive.com/wp-content/uploads/2018/03/VariableTarget.png)

Switch to the task inspector and assign that variable to the two tasks:

![](https://opsive.com/wp-content/uploads/2018/03/VariableMoveTowards.png)

And with that the two tasks can start to share information! You can get/set the value of the shared variable by accessing the Value property. For example:

```csharp
Transform transformValue = target.Value;
```

will return the transform object. When Within Sight runs it will assign the transform of the object that comes within sight to the Target variable. When Move Towards runs it will use that Target variable to determine what position to move towards. Looking at the variable within the inspector, if you look to the left of the delete button you'll see a triangle pointing to the right. This is the button for Variable Mappings.

![](https://opsive.com/wp-content/uploads/2018/03/VariableMapping.png)

Variable Mappings allow your SharedVariable to map to a property of the same type. This allows you to quickly get or set a value on a MonoBehaviour component. As an example, lets say that we want to get the position of the agent. It is possible to use the Get Position task with a non-mapped variable, but that adds unnecessary tasks to your behavior tree. Instead, if you map the variable to the Transform.position property, whenever the value of the variable is accessed, it will instead use the property that it is mapped to. This allows you to get or set the position of the Transform without any extra tasks. **Note**: Variable Mappings require a C# property. It does not work on C# fields. With the above Vector3 example, you can setup a property mapping with the following:

```csharp
public class MyMonoBehaviour : MonoBehaviour
{
   private Vector3 m_MyVector3;
   public Vector3 MyVector3 { get { return m_MyVector3; } set { m_MyVector3 = value; } } // Required for property mappings.
}
```

Behavior Designer supports both local and global variables. [Global Variables](https://opsive.com/support/documentation/behavior-designer/variables/global-variables/) are similar to local variables except any tree can reference the same variable. Variables can be referenced by non-Task derived classes by [getting a reference](https://opsive.com/support/documentation/behavior-designer/variables/accessing-variables-from-non-task-objects/) to from the behavior tree. The following shared variable types are included in the default Behavior Designer installation. If none of these types are suitable for your situation then you can [create your own shared variable](https://opsive.com/support/documentation/behavior-designer/variables/creating-shared-variables/):

-   SharedAnimationCurve
-   SharedBool
-   SharedColor
-   SharedFloat
-   SharedGameObject
-   SharedGameObjectList
-   SharedInt
-   SharedMaterial
-   SharedObject
-   SharedObjectList
-   SharedQuaternion
-   SharedRect
-   SharedString
-   SharedTransform
-   SharedTransformList
-   SharedVector2
-   SharedVector3Int
-   SharedVector3
-   SharedVector3Int
-   SharedVector4

---

<a id="page-behavior-designer-variables-dynamic-variables"></a>

# Dynamic Variables

[View this page online](https://opsive.com/support/documentation/behavior-designer/variables/dynamic-variables/)

Dynamic variables allow you to use temporary variables that are limited in scope. These variables are great if you want to share data between a limited number of tasks and do not need to access the variable outside of those tasks. Dynamic variables can be created by clicking the circle to the right of the variables field and then selecting "(Dynamic)":

![](https://opsive.com/wp-content/uploads/2018/10/DynamicVariableSelection.png)

After the dynamic variable has been created you can then type the name of the variable.

![](https://opsive.com/wp-content/uploads/2018/10/DynamicVariableName.png)

The dynamic variable will now be used within your tree. The dynamic variable will have the same value for any fields that reference the same dynamic variable name. The name is case sensitive and should not be the same as a local variable within the tree.

---

<a id="page-behavior-designer-variables-global-variables"></a>

# Global Variables

[View this page online](https://opsive.com/support/documentation/behavior-designer/variables/global-variables/)

Global variables are similar to local variables except any behavior tree can access an instance of the same variable. To access global variables, navigate to the Window->Behavior Designer->Global Variables menu option or from within the Variables pane:

![](https://opsive.com/wp-content/uploads/2018/03/GlobalVariables.png)

When a global variable is first added an asset file is created which stores all of the global variables. This file is created at /Behavior Designer/Resources/BehaviorDesignerGlobalVariables.asset. You can move this file as long as it is still located in a Resources folder. Global variables are assigned in a very similar way as local variables. In the task inspector, when you are assigning a global variable the global variables are located under the "Globals" menu item:

![](https://opsive.com/wp-content/uploads/2018/03/GlobalVariablesSelection.png)

Global variables can also be [accessed from non-Task derived objects](https://opsive.com/support/documentation/behavior-designer/variables/accessing-variables-from-non-task-objects/).

---

<a id="page-behavior-designer-variables-creating-shared-variables"></a>

# Creating Shared Variables

[View this page online](https://opsive.com/support/documentation/behavior-designer/variables/creating-shared-variables/)

New Shared Variables can be created if you don't want to use any of the built in types. To create a Shared Variable, subclass the SharedVariable type and implement the following methods. The keyword OBJECT\_TYPE should be replaced with the type of Shared Variable that you want to create.

```csharp
[System.Serializable]
public class SharedOBJECT_TYPE : SharedVariable<OBJECT_TYPE>
{
   public static implicit operator SharedOBJECT_TYPE(OBJECT_TYPE value) { return new SharedOBJECT_TYPE { Value = value }; }
}
```

It is important that the "Value" property exists. The variable inspector will show an error if the new Shared Variable is created incorrectly. Shared Variables can contain any type of object that your task can contain, including primitives, arrays, lists, custom objects, etc. As an example, the following script will allow a custom class to be shared:

```csharp
    [System.Serializable]
    public class CustomClass
    {
        public int myInt;
        public Object myObject;
    }

    [System.Serializable]
    public class SharedCustomClass : SharedVariable<CustomClass>
    {
        public static implicit operator SharedCustomClass(CustomClass value) { return new SharedCustomClass { Value = value }; }
    }
```

---

<a id="page-behavior-designer-variables-accessing-variables-from-non-task-objects"></a>

# Accessing Variables from non-Task Objects

[View this page online](https://opsive.com/support/documentation/behavior-designer/variables/accessing-variables-from-non-task-objects/)

Variables are normally referenced by [assigning](https://opsive.com/support/documentation/behavior-designer/variables/) the variable name to the task field within the Behavior Designer inspector panel. Local variables can also be accessed by non-Task derived classes (such as MonoBehaviour) by calling the method:

```csharp
behaviorTree.GetVariable("MyVariable");
behaviorTree.SetVariable("MyVariable", value);
behaviorTree.SetVariableValue("MyVariableName", value);
```

When setting a variable, if you want the tasks to automatically reference that variable then make sure a variable is created with that name ahead of time. The following code snippet shows an example of modifying a variable from a MonoBehaviour class:

```csharp
using UnityEngine;
using BehaviorDesigner.Runtime;

public class AccessVariable : MonoBehaviour
{
   public BehaviorTree behaviorTree;

   public void Start()
   {
      var myIntVariable = (SharedInt)behaviorTree.GetVariable("MyVariable");
      myIntVariable.Value = 42;
   }
}
```

In the above example we are getting a reference to the variable named "MyVariable" within the Behavior Designer Variables pane. Also, as shown in the example, you can get and set the value of the variable with the SharedVariable.Value property. Similarly, global variables can be accessed by getting a reference to the GlobalVariable instance:

```csharp
GlobalVariables.Instance.GetVariable("MyVariable");
GlobalVariables.Instance.SetVariable("MyVariable", value);
```

All variables can be retrieved with:

```csharp
var variables = BehaviorTree.GetAllVariables();
```

---

<a id="page-behavior-designer-conditional-aborts"></a>

# Conditional Aborts

[View this page online](https://opsive.com/support/documentation/behavior-designer/conditional-aborts/)

https://www.youtube.com/watch?v=GFsK5x6ZW7k Conditional aborts allow your behavior tree to dynamically respond to changes without having to clutter your behavior tree with many Interrupt/Perform Interrupt tasks. This feature is similar to the Observer Aborts in Unreal Engine 4. Most behavior tree implementations reevaluate the entire tree every tick. Conditional aborts are an optimization to prevent having to rerun the entire tree. As a basic example, consider the following tree:

![](https://opsive.com/wp-content/uploads/2018/03/ConditionalAbortBasicTree.png)

When this tree runs the Conditional task will return success and the Sequence task will start running the next child, the Wait task. The Wait task has a wait duration of 10 seconds. While the wait task is running, lets say that the conditional task changes changes state and now returns failure. If Conditional aborts are enabled, the Conditional task will issue an abort and stop the Wait task from running. The Conditional task will be reevaluated and the next task will run according to the standard behavior tree rules. Conditional aborts can be accessed from any Composite task:

![](https://opsive.com/wp-content/uploads/2018/03/ConditionalAbortSelfTree.png)

There are four different abort types: None, Self, Lower Priority, and Both.

| None | Self |
| --- | --- |
|
**Lower Priority**![](https://opsive.com/wp-content/uploads/2018/03/ConditionalAbortLowerPriority.png) Behavior trees can be organized from more important tasks to least important. If a more important Conditional task changes status then can issue an abort that will stop the lower priority tasks from running.

 | **Both**![](https://opsive.com/wp-content/uploads/2018/03/ConditionalAbortBoth.png) This abort type combines both self and lower priority. |

Conditional aborts can also be thought of the following way: **Lower Priority:** will reevaluate when any task to the right of the current branch is active. **Self:** will reevaluate when any task within the current branch is active. **Both:** will reevaluate when any task to the right or within the current branch is active. The following example will use the lower priority abort type:

![](https://opsive.com/wp-content/uploads/2018/03/ConditionalAbortLowerPriorityTree.png)

In this example the parent Sequence task of the left branch has an abort type of lower priority. Lets say that the left branch fails and moves the tree onto the right branch due to the Selector parent task. While the right branch is running, the very first Conditional task changes status to success. Because the task status changed and the abort type was lower priority the Action task that is currently running gets aborted and the original Conditional task is rerun. The conditional task's execution status will have a repeater icon around the success or failure status to indicate that it is being reevaluated by a conditional abort:

![](https://opsive.com/wp-content/uploads/2018/03/ConditionalAbortReevaluate.png)

Conditional aborts can be nested beneath one another as well. For example, you may want to run a branch when one of two conditions succeed, but they both don't have to. In this example we will be using the Can See Object and Can Hear Object tasks. You want to run the action task when the object is either seen or heard. To do this, these two conditional tasks should be parented by a Selector with the lower priority abort type. The action task is then a sibling of the Selector task. A Sequence task is then parented to these two tasks because the action task should only run when either of the conditional tasks succeed. The Sequence task is set to a Lower Priority abort type so the two conditional tasks will continue to be reevaluated even when the tree is running a completely different branch.

![](https://opsive.com/wp-content/uploads/2018/03/ConditionalAbortRecursive.png)

The important thing to note with this tree is that the Selector task must have an abort type set to Lower Priority (or Both). If it does not have an abort type set then the two conditional tasks would not be reevaluated.

---

<a id="page-behavior-designer-events"></a>

# Events

[View this page online](https://opsive.com/support/documentation/behavior-designer/events/)

The event system within Behavior Designer allows your behavior trees to easily react to changes. This event system can trigger an event via code or through behavior tree tasks. Events can be signaled through the behavior tree with the Send Event and the Has Received Event tasks. When an event should be signaled, the Send Event task should be used. The Has Received Event task is a conditional task and will return success as soon as the event has been received. An event name can be specified for both of these tasks. In order to properly receive the events the Has Received Event task should be reevaluated with conditional aborts. As an example, consider the following tree:

![](https://opsive.com/wp-content/uploads/2018/03/Events.png)

During the first tick the Has Received Event task will fail because the event has not been received yet. The Selector will then move to the right branch and the Wait task will start. After a second the Send Event Task will send the event and then Idle is started to keep the tree active. During the next tick the Has Received Event task returns a status of success because of the previous event that was sent. It then outputs the value of the MyInt variable which was sent with the Send Event task.

<div class="woocommerce-message docs-info">The&nbsp;<em>Target GameObject</em> variable on the Send Event task must contain a behavior tree. The task will return failure if the <em>Target GameObject</em> does not have a behavior tree.</div>

In addition to being able to send events via the behavior tree, events can be sent through code. The BehaviorTree.SendEvent method will allow you to send an event to the specified behavior tree. For example:

```csharp
var behaviorTree = GetComponent<BehaviorTree>();
behaviorTree.SendEvent<int>("MyEvent", 5);
```

In this example the "MyEvent" event will be sent to the behavior tree component with a parameter value of 5. If the behavior tree contains the Has Received Event task then it will react accordingly. You are also able to receive events from outside the behavior tree. To continue with the "MyEvent" example, you can receive this event by using the BehaviorTree.RegisterEvent method. BehaviorTree.UnregisterEvent will stop listening for that event.

```csharp
public void OnEnable()
{
   var behaviorTree = GetComponent<BehaviorTree>();
   behaviorTree.RegisterEvent<int>("MyEvent", ReceivedEvent);
}

public void ReceivedEvent(object arg1)
{

}

public void OnDisable()
{
   var behaviorTree = GetComponent<BehaviorTree>();
   behaviorTree.UnregisterEvent<int>("MyEvent", ReceivedEvent);
}
```

---

<a id="page-behavior-designer-external-behavior-trees"></a>

# External Behavior Trees

[View this page online](https://opsive.com/support/documentation/behavior-designer/external-behavior-trees/)

![](https://opsive.com/wp-content/uploads/2018/03/ExternalAsset.png)

In some cases you may have a behavior tree that you want to run from multiple objects. For example, you could have a behavior tree that patrols a room. Instead of creating a separate behavior tree for each unit you can instead use an external behavior tree. An external behavior tree is referenced using the Behavior Tree Reference task. When the original behavior tree starts running it will load all of the tasks within the external behavior tree and act like they are its own. Any SharedVariable within the external tree of the same name and type of its parent tree will automatically be overridden. For example, if the parent tree has a SharedInt named "MyInt" with a value of 7, and the External Tree has a SharedInt named "MyInt" with a value of 0, when the tree runs MyInt will have a value of 7 within the External Tree.

### Behavior Tree Reference

The Behavior Tree Reference task allows you to run another behavior tree within the current behavior tree. You can create this behavior tree by saving the tree as an external behavior tree. One use for this is that if you have an unit that plays a series of tasks to attack. You may want the unit to attack at different points within the behavior tree, and you want that attack to always be the same. Instead of copying and pasting the same tasks over and over you can just use an external behavior and then the tasks are always guaranteed to be the same. This example is demonstrated in the RTS sample project located on the [samples page](/integrations/?pid=803). The GetExternalBehaviors method allows you to override it so you can provide an external behavior tree array that is determined at runtime. The Behavior Tree Reference task allows you to specify variables per-reference task. For most cases this is not needed because variables will automatically be transferring from the parent tree to the External Tree. However, if you have multiple Behavior Tree Reference tasks in the same tree all pointing to the same External Tree, you may want to be able to specify different variable values per tree. In this situation you can specify the variable value on the Behavior Tree Reference task and that variable value will be transferred to the External Tree.

### Pooling

External behavior trees can be pooled for better performance when switching between many external trees. When the external behavior tree is instantiated the Init method should be called to deserialize the external behavior tree. Pooled external behavior trees can then be assigned to the behavior tree component just like non pooled external behavior trees. For example:

```csharp
using UnityEngine;
using BehaviorDesigner.Runtime;

public class ExternalPoolExample : MonoBehaviour {
    public BehaviorTree behaviorTree;
    public ExternalBehavior externalBehaviorTree;

    private ExternalBehavior[] externalPool;
    private int index;

    public void Awake()
    {
        // Instantiate five External Behavior Tree which will be reused. The Init method will deserialize the External Behavior Tree.
        externalPool = new ExternalBehavior[5];
        for (int i = 0; i < externalPool.Length; ++i) {
            externalPool[i] = Object.Instantiate(externalBehaviorTree);
            externalPool[i].Init();
        }
    }

    public void OnGUI()
    {
        // Assign the next External Behavior Tree within the simplified pool.
        if (GUILayout.Button("Assign")) {
            behaviorTree.DisableBehavior();
            behaviorTree.ExternalBehavior = externalPool[index];
            behaviorTree.EnableBehavior();
            index = (index + 1) % externalPool.Length;
        }
    }
}
```

---

<a id="page-behavior-designer-networking"></a>

# Networking

[View this page online](https://opsive.com/support/documentation/behavior-designer/networking/)

Behavior Designer supports Unity's networking system UNET introduced with Unity 5.1. Networking is a complex topic so it is highly recommended that you first go through Unity's [networking documentation](http://docs.unity3d.com/Manual/UNetOverview.html) before continuing. Note: UNET has been deprecated in current versions of Unity. This guide is for those using older Unity versions. Shared Variables can automatically be synchronized over the network from the server to the client. This can be enabled by opening the details of the variable and selecting "Network Sync":

![](https://opsive.com/wp-content/uploads/2018/03/VariableNetworkSync.png)

The ENABLE\_MULTIPLAYER [compiler definition](http://docs.unity3d.com/Manual/PlatformDependentCompilation.html) must be added for the variables to sync correctly. Due to a current networking limitation, ClientRPC calls cannot be overloaded so the type has to be known ahead of time. This means that only the following types of variables can be synchronized:

-   bool
-   Color
-   float
-   GameObject
-   int
-   Quaternion
-   Rect
-   string
-   Transform
-   Vector2
-   Vector3
-   Vector4

The Behavior component from the [runtime source code](https://opsive.com/support/documentation/behavior-designer/installation/) must be used in order to allow the variables to be synchronized. This is a result of a current Unity networking bug. ClientRPC calls cannot be called on the parent class from a subclass. A bug report has been submitted and are waiting for a fix. This bug manifests itself by displaying the following warning in the console: _Failed to invoke RPC \[RpcPath\](\[ObjectID\]) on netID \[NetID\]_ Where \[RpcPath\] is the method path, \[ObjectID\] is the ID of the object, and \[NetID\] is the network ID.

---

<a id="page-behavior-designer-referencing-tasks"></a>

# Referencing Tasks

[View this page online](https://opsive.com/support/documentation/behavior-designer/referencing-tasks/)

When writing a new task, in some cases it is necessary to access another task within that task. For example, TaskA may want to get the value of TaskB.SomeFloat. To accomplish this, TaskB needs to be referenced from TaskA. In this example TaskA looks like:

```csharp
using UnityEngine;
using BehaviorDesigner.Runtime.Tasks;

public class TaskA : Action
{
   public TaskB referencedTask;

   public void OnAwake()
   {
      Debug.Log(referencedTask.SomeFloat);
   }
}
```

TaskB then looks like:

```csharp
using UnityEngine;
using BehaviorDesigner.Runtime.Tasks;

public class TaskB : Action
{
   public float SomeFloat;
}
```

Add both of these tasks to your behavior tree within Behavior Tree and select TaskA.

![](https://opsive.com/wp-content/uploads/2018/03/ReferencedTask.png)

Click the select button. You'll enter a link mode where you can select other tasks within the behavior tree. After you select Task B you'll see that Task B is linked as a referenced task:

![](https://opsive.com/wp-content/uploads/2018/03/ReferencedTaskLinked.png)

That is it. Now when you run the behavior tree TaskA will be able to output the value of TaskB's SomeFloat value. You can clear the reference by clicking on the "x" to the right of the referenced task name. If you click on the "i" then the linked task will highlight in orange:

![](https://opsive.com/wp-content/uploads/2018/03/ReferencedTaskIdentified.png)

Tasks can also be referenced using an array:

```csharp
public class TaskA : Action
{
   public TaskB[] referencedTasks;
}
```

---

<a id="page-behavior-designer-object-drawers"></a>

# Object Drawers

[View this page online](https://opsive.com/support/documentation/behavior-designer/object-drawers/)

Object Drawers are very similar to the Unity feature [Property Drawers](http://docs.unity3d.com/Manual/editor-PropertyDrawers.html). Object drawers allow you to customize the look of different objects within the inspector. As an example, we will modify the Shared Custom Object example found in the [Creating Your Own Shared Variable](https://opsive.com/support/documentation/behavior-designer/variables/creating-shared-variables/) topic. With the default inspector, the SharedCustomClass variable looks like the following in the inspector:

![](https://opsive.com/wp-content/uploads/2018/03/CustomClassDefaultInspector.png)

For this example, we will limit the range of the integer between 0 and 10 using object drawers:

![](https://opsive.com/wp-content/uploads/2018/03/CustomClassObjectDrawer.png)

The following object drawer was used to accomplish this (this script goes in an Editor folder):

```csharp
using UnityEngine;
using UnityEditor;
using BehaviorDesigner.Editor;

[CustomObjectDrawer(typeof(CustomClass))]
public class CustomClassDrawer : ObjectDrawer
{
   public override void OnGUI(GUIContent label)
   {
      var customClass = value as CustomClass;
      EditorGUILayout.BeginVertical();
      if (FieldInspector.DrawFoldout(customClass.GetHashCode(), label)) {
         EditorGUI.indentLevel++;
         customClass.myInt = EditorGUILayout.IntSlider("Integer", customClass.myInt, 0, 10);
         customClass.myObject = EditorGUILayout.ObjectField("Object", customClass.myObject, typeof(UnityEngine.Object), true);
         EditorGUI.indentLevel--;
      }
      EditorGUILayout.EndVertical();
   }
}
```

The only method that you need to override for object drawers to work is the OnGUI(GUIContent label) method. The label field is the name of the field that is being drawn. Just like property drawers, you can specify a object drawer by the class type or by attributes. The example above is using the class type method. As another example, we will convert the Ranged Attribute used in Unity's example to a Object Drawer. First we need to create the attribute:

```csharp
using UnityEngine;
using BehaviorDesigner.Runtime.Tasks;
using BehaviorDesigner.Runtime.ObjectDrawers;

public class RangeAttribute : ObjectDrawerAttribute
{
   public float min;
   public float max;

   public RangeAttribute(float min, float max)
   {
      this.min = min;
      this.max = max;
   }
}
```

Now that the attribute is created, we need to create the actual object drawer (this script goes in an Editor folder):

```csharp
using UnityEngine;
using UnityEditor;
using BehaviorDesigner.Editor;

[CustomObjectDrawer(typeof(RangeAttribute))]
public class RangeDrawer : ObjectDrawer
{
   public override void OnGUI(GUIContent label)
   {
      var rangeAttribute = (RangeAttribute)attribute;
      value = EditorGUILayout.Slider(label, (float)value, rangeAttribute.min, rangeAttribute.max);
   }
}
```

Once both of these have been created, we can use it within a task:

```csharp
using UnityEngine;
using BehaviorDesigner.Runtime;
using BehaviorDesigner.Runtime.Tasks;
using BehaviorDesigner.Runtime.ObjectDrawers;

public class NewAction : Action
{
   [Range(5, 10)]
   public float rangedFloat;
   public override TaskStatus OnUpdate()
   {
      Debug.Log(rangedFloat);
      return TaskStatus.Success;
   }
}
```

This will show up in the task inspector as:

![](https://opsive.com/wp-content/uploads/2018/03/AttributeObjectDrawer.png)

---

<a id="page-behavior-designer-variable-synchronizer"></a>

# Variable Synchronizer

[View this page online](https://opsive.com/support/documentation/behavior-designer/variable-synchronizer/)

[Shared Variables](https://opsive.com/support/documentation/behavior-designer/variables/) are great for sharing data across tasks and behavior trees. However, in some cases you want to share to same variables with non-behavior tree components. As an example, you may have a GUI Controller component which manages the GUI. This GUI Controller displays a GUI element indicating whether or not the agent being controlled by the behavior tree is alive. It does this by having a boolean which says whether or not the agent is alive:

```csharp
public bool isAlive { get; set; }
```

With the Variable Synchronizer component, you can automatically keep this boolean and the corresponding Shared Variable synchronized with each other. To setup the Variable Synchronizer, first make sure you have created the Shared Variables that you want to synchronize. For this example we created three Shared Variables:

![](https://opsive.com/wp-content/uploads/2018/03/VariableSynchronizerVariables.png)

Following that, add the Behavior Designer/Variable Synchronizer component to a GameObject.

![](https://opsive.com/wp-content/uploads/2018/03/VariableSynchronizerBlank.png)

Next, start adding the Shared Variable that you want to keep synchronized. For this example we are going to add the Is Alive variable that was previously mentioned.

![](https://opsive.com/wp-content/uploads/2018/03/VariableSynchronizerAdd.png)

1.  Specify the GameObject which contains the behavior tree that has the Shared Variable that you want to synchronize.
2.  Select from the popup box which Shared Variable you want to use.
3.  Specify a direction. If the arrow is pointing to the left then you are setting the Shared Variable value. If the arrow is pointing to the right then you are getting the Shared Variable value.
4.  Specify the type of synchronization. Currently the following types are supported: Behavior Designer, Property, Animator, and PlayMaker.
5.  The remaining steps will depend on the type of synchronization selected. In this example Property was selected so you'll need to select the component which contains the property that you want to synchronize with the Shared Variable.
6.  Click Add.

Once added the Is Alive Shared Variable will set the isAlive property at an interval specified by Update interval. The following screenshot contains a few more synchronized variables:

![](https://opsive.com/wp-content/uploads/2018/03/VariableSynchronizerVariableList.png)

-   The Is Alive Shared Variable is setting the isAlive property.
-   The Speed Share Variable is setting the Speed Animator parameter.
-   The Target Shared Variable is being set by the Target PlayMaker variable.

---

<a id="page-behavior-designer-syncing-animations"></a>

# Syncing Animations

[View this page online](https://opsive.com/support/documentation/behavior-designer/syncing-animations/)

Behavior Designer includes a set of Animator tasks which allow you to play animations within the tree. Consider the tree below:

![](https://opsive.com/wp-content/uploads/2018/03/SyncAnimationsBlendTree.png)

This is an extremely simple Animator Controller that uses a blend tree to blend between the Idle and Run state based on the Speed parameter. If you'd like to then sync this blend tree with the Seek task your behavior tree would then look similar to:

![](https://opsive.com/wp-content/uploads/2018/03/SyncAnimationsTree.png)

Before the Seek task starts the Speed parameter is set to 1 so the blend tree can play the run animation. After the Seek task completes the Speed parameter is then set to 0 to play the Idle animation again. With a small behavior tree and Animator Controller this process works well. However, as the amount of animations grow for your agent this method starts to become extremely cumbersome. In addition, your behavior tree also starts to become extremely verbose with all of the Animator tasks and if you change a transition within your Animator Controller you'd have to rework the behavior tree to work with that Animator Controller change. There is a better way. The recommended approach to syncing animations within your behavior tree is to not sync the animations at all within the behavior tree. Instead your agent's character controller should do it for you. Using Unity's NavMeshAgent as an example, when the behavior tree sets the NavMeshAgent destination (such as with the Seek task) the NavMeshAgent's velocity will change to move towards the destination. The character controller should then use the velocity and translate the movements into parameters that the Animator Controller can understand. MecWarriors had an excellent tutorial on how to accomplish this. The MecWarriors site is no longer operational but a cached version of the tutorial can be found [here](https://web.archive.org/web/20160317180801/http://mecwarriors.com/2014/12/09/navmesh-and-mecanim/). Unity also has a similar tutorial within [their documentation](https://docs.unity3d.com/Packages/com.unity.ai.navigation@1.1/manual/CouplingAnimationAndNavigation.html). A similar implementation can be done with A\* Pathfinding Project. The advantage of this approach is that your behavior tree is then not aware of the animations at all and it can even work with [root motion](https://docs.unity3d.com/Manual/RootMotion.html). You also don't over-complicate your tree with Animator tasks and makes your tree a lot cleaner. The [Ultimate Character Controller](https://assetstore.unity.com/packages/slug/233710?aid=1100lGdc) uses this approach and for that asset we created a pretty large behavior tree. You can see the behavior tree on [this page](https://opsive.com/support/documentation/behavior-designer/integrations/opsive-character-controllers/) and you'll notice that there are no Animator tasks within the tree. A bridge component is linking the NavMeshAgent's velocity to the character controller's inputs which then allow the Ultimate Character Controller to take care of the animations.

---

<a id="page-behavior-designer-referencing-scene-objects"></a>

# Referencing Scene Objects

[View this page online](https://opsive.com/support/documentation/behavior-designer/referencing-scene-objects/)

As you are creating your tree it is common practice to reference objects within the scene from a Shared Variable or task. For example, in this tree Can See Object is determining if the Enemy object can be seen:

![](https://opsive.com/wp-content/uploads/2018/03/SceneObjectRefenceCanSeeOriginal.png)

As you are testing you find that everything is working well and now you'd like to make a prefab out of it so you can have multiple agents in your scene. As soon as you make the agent a prefab and remove it from the scene you'll find that the Target Object reference has gone missing. The reason this occurs is because as a project level asset (the prefab, or global variables file) cannot reference objects in the scene. This is a Unity restriction and the way to overcome it is to populate the variable at runtime after you have spawned the prefab. The scene reference object can be populated at runtime in many different ways. One way is to use the Find task and search for the object by name:

![](https://opsive.com/wp-content/uploads/2018/03/SceneObjectRefenceTree.png)

 

![](https://opsive.com/wp-content/uploads/2018/03/SceneObjectReferenceFindValues.png)

![](https://opsive.com/wp-content/uploads/2018/03/SceneObjectRefenceCanSeeValues.png)

When the Find task runs it'll search for a GameObject named "Enemy" and then place it in a SharedVariable. When Can See Object runs it'll then use that SharedVarible to search for the target object. Another way to populate the value at runtime is to have a component already in the scene which has a reference to the object. After the prefab has been spawned this component can then set the value of a SharedVariable that the Can See Object uses.

```csharp
using UnityEngine;
using BehaviorDesigner.Runtime;

public class Spawner : MonoBehaviour
{
    public GameObject m_Enemy;

    public void Start()
    {
        var behaviorTree = GetComponent<BehaviorTree>();
        behaviorTree.SetVariableValue("Enemy", m_Enemy);
    }
}
```

---

<a id="page-behavior-designer-task-attributes"></a>

# Task Attributes

[View this page online](https://opsive.com/support/documentation/behavior-designer/task-attributes/)

Behavior Designer exposes the following task attributes: HelpURL, TaskIcon, TaskCategory, TaskDescription and LinkedTask.

### Help URL

If you open the task inspector panel you will see on the doc icon on the top right. This doc icon allows you to associate a help webpage with a task. You make this association with the HelpURL attribute. The HelpURL attribute takes one parameter which is the link to the webpage.

```csharp
[HelpURL("http://www.example.com")]
public class MyTask : Action
{
```

### Task Icon

Task icons are shown within the behavior tree using the TaskIcon attribute and are used to help visualize what a task does. Paths are relative to the root project folder. The keyword {SkinColor} will be replaced by the current Unity skin color, "Light" or "Dark".

```csharp
[TaskIcon("Assets/Path/To/{SkinColor}Icon.png")]
public class MyTask : Action
{
```

### Task Name

The default task name can be changed with the TaskName attribute. This will change the displayed name when the task is added and also within the task list.

```csharp
[TaskName("MyCoolTask")]
public class MyTask : Action
{
```

### Task Category

Organization starts to become an issue as you create more and more tasks. For that you can use TaskCategory attribute:

```csharp
[TaskCategory("Common")]
public class Seek : Action
{
```

This task will now be categorized under the common category:

![](https://opsive.com/wp-content/uploads/2018/03/TaskCategory.png)

Categories can be nested by separating the category name with a slash:

```csharp
[TaskCategory("RTS/Harvester")]
public class HarvestGold : Action
{
```

### Task Description

The TaskDescription attribute allows you to show your class-level comment within the graph view. For example, the sequence description starts out with:

```csharp
[TaskDescription("The sequence task is similar to an \"and\" operation. ..."]
public class Sequence : Composite
{
```

This description will then be shown in the bottom left area of the graph:

### ![](https://opsive.com/wp-content/uploads/2018/03/TaskDescription.png) Linked Task

[Variables](https://opsive.com/support/documentation/behavior-designer/variables/) are great when you want to share information between tasks. However, you'll notice that there is no such thing as a "SharedTask". When you want a group of tasks to share the same tasks use the LinkedTask attribute. As an example, take a look at the task guard task. When you reference one task with the task guard, that same task will reference the original task guard task back. Linking tasks is not necessary, it is more of a convince attribute to make sure the fields have values that are synchronized. Add the following attribute to your field to enable task linking:

```csharp
[LinkedTask]
public TaskGuard[] linkedTaskGuards = null;
```

To perform a link within the editor perform the same steps as [referencing another task](https://opsive.com/support/documentation/behavior-designer/referencing-tasks/).

---

<a id="page-behavior-designer-integrations"></a>

# Integrations

[View this page online](https://opsive.com/support/documentation/behavior-designer/integrations/)

Behavior Designer includes many tasks which integrate with third party assets. For most of those integrations, no extra steps are required and they can be added to a behavior tree and then have their values assigned. However, the integrations below have a more detailed explanation for how they work. [Dialogue System for Unity](https://opsive.com/support/documentation/behavior-designer/integrations/dialogue-system-for-unity/) [Playmaker](https://opsive.com/support/documentation/behavior-designer/integrations/playmaker/) [Ultimate Character Controller](https://opsive.com/support/documentation/behavior-designer/integrations/opsive-character-controllers/) [uScript](https://opsive.com/support/documentation/behavior-designer/integrations/uscript/)

---

<a id="page-behavior-designer-integrations-dialogue-system-for-unity"></a>

# Dialogue System

[View this page online](https://opsive.com/support/documentation/behavior-designer/integrations/dialogue-system-for-unity/)

The [Dialogue System](https://assetstore.unity.com/packages/tools/ai/dialogue-system-for-unity-11672?aid=1100lGdc) is a complete dialogue system for Unity. Behavior Designer is integrated with the Dialogue System by allowing you to manage conversations, barks, sequences, and quests within your behavior tree. Also, Dialogue System is integrated with Behavior Designer so it can synchronize variables with Lua and start/stop behavior trees with sequence commands. More information on this side of the integration can be found [here](http://www.pixelcrushers.com/dialogue_system/manual/html/behavior_designer.html). All of the Dialogue System integration files are located on the [downloads page](/downloads/). To get started, first make sure you have Dialogue System for Unity installed and have imported the integration package. Once those files are imported you are ready to start creating behavior trees with the Dialogue System. Let's create a very basic tree with a sequence task which has a Wait task and a Start Conversation task:

![](https://opsive.com/wp-content/uploads/2018/04/DialogueSystemStartConversationTree.png)

When the Dialogue System finishes with a conversation or sequence it will callback to Behavior Designer to let Behavior Designer know that it is done. In order for this to occur the Dialogue System Callback component must be added to the same GameObject that your behavior tree is on:

![](https://opsive.com/wp-content/uploads/2018/04/DialogueSystemCallback.png)

Now we are ready to start creating the actual conversion. Create a new Dialogue System Database and create a basic conversation:

![](https://opsive.com/wp-content/uploads/2018/04/DialogueSystemMainConversationDatabase.png)

Make note of the conversation name because that will be needed later. Assign that database to the Dialogue System Controller:

![](https://opsive.com/wp-content/uploads/2018/04/DialogueSystemController.png)

The last step is to simply assign the values within the Start Conversation task. The only two values that are required are the conversation name and the actor GameObject:

![](https://opsive.com/wp-content/uploads/2018/04/DialogueSystemConverstionTaskInspector.png)

Once those values have been assigned, hit play and you'll see the text "Hello World" appear at the top of the game screen:

![](https://opsive.com/wp-content/uploads/2018/04/DialogueSystemHelloWorld.png)

This topic hardly scratches the surface for what is possible with Behavior Designer / Dialogue System integration. For a more complex example, take a look at the Dialogue System sample project.

---

<a id="page-behavior-designer-integrations-opsive-character-controllers"></a>

# Opsive Character Controllers

[View this page online](https://opsive.com/support/documentation/behavior-designer/integrations/opsive-character-controllers/)

https://www.youtube.com/watch?v=W5Of1lC-L68 **This integration package can be downloaded on the [downloads page](/downloads/).** The Opsive Character Controllers are integrated with Behavior Designer allowing your AI to perform any function that a player-controlled character can perform. When you are creating a new character that should be used with Behavior Designer ensure you have enabled AI Agent within the Character Manager. If you are using Unity's Navigation Mesh you should also enabled the NavMeshAgent toggle.

![](https://opsive.com/wp-content/uploads/2018/04/AIAgentBuilder.png)

After the character has been created the Behavior Tree Agent Setup should be run on the character. This can be found within the Opsive Character Controller [integration package](/downloads/).

![](https://opsive.com/wp-content/uploads/2018/04/BehaviorDesignerAgentSetup.png)

The Agent Setup editor will add the Behavior Tree and Behavior Tree Agent components. In the demo scene you'll notice that there is also a Demo Agent component added which adds the character's health and ammo as property's for Behavior Designer's [Property Mapping](https://opsive.com/support/documentation/behavior-designer/variables/) feature. After the character has been setup it's time to create your own behavior tree. The included behavior tree provides a great overview of the behavior tree flow so the rest of this document will describe how that behavior tree works. In order to get the most out of Behavior Designer it is highly recommended that you create your own behavior tree. The included behavior tree will perform the following functions:

-   Attack if the player is within sight.
-   Attack if the player attacks the agent.
-   Move towards the audio source location if a sound from the player is heard.
-   Search for the player if the player is lost.
-   Get health if needed.
-   Get ammo if needed.
-   Patrol if no other actions are necessary.

The entire behavior tree looks like:

![](https://opsive.com/wp-content/uploads/2018/04/UltimateCharacterControllerTree-1024x312.png)

Behavior trees evaluate from top to bottom, left to right. This means that the very first task that runs is the Sequence task directly beneath the Entry task:

![](https://opsive.com/wp-content/uploads/2018/04/UltimateCharacterControllerTreeStartTasks.png)

The Sequence task is a Composite task that will evaluate all of its children until a child returns a status of failure. The Sequence task can be thought of an AND between the child tasks. The first three tasks that this Sequence task will execute relate to resetting the behavior tree to get it ready for the next run. The variables that these tasks are resetting will be described later. A Parallel task is then used to execute multiple children at the same time. There are two branches that this Parallel task will execute:

-   Left branch which will perform the actual actions such as the movement or attack.
-   Right branch which will keep the player's location up to date when the Update Position variable is true.

The main functionality of the tree is contained within the left branch:

![](https://opsive.com/wp-content/uploads/2018/04/UltimateCharacterControllerTreeMainBranch-1024x246.png)

This branch is parented with a Repeater task which is set to Repeat Forever. The Repeater task is a Decorator which will keep executing the child branch for as long as requested. Since Repeat Forever is enabled the Repeater will keep the branch active until the bheavior tree ends. A Selector is parented to the Repeater. The Selector task will execute its children until a child returns success. The Selector can be thought of as as OR between the child tasks. Because behavior trees evaluate from left to right the branches on the left have a higher priority than those on the right. This means that the very first branch that will execute is the branch that checks to determine if the agent is out of ammo:

![](https://opsive.com/wp-content/uploads/2018/04/UltimateCharacterControllerTreeAmmoBranch.png)

The Sequence task of the ammo branch has a Lower Priority [Conditional Abort](https://opsive.com/support/documentation/behavior-designer/conditional-aborts/) set. Conditional Aborts allow the behavior tree to reevaluate child Conditional tasks when other branches are active. If the character is out of ammo then the character can't do anything so this branch has the highest priority. If a lower priority branch (any branch to the right of the ammo branch) is active and the agent runs low on ammo then the conditional abort will abort the lower priority branch and start executing the ammo branch. The ammo branch is a relatively simple branch that first checks to determine how much ammo the character has with the Int Comparison Conditional task. This Int Comparison task will compare the agent's ammo to a constant number. The amount of ammo is retrieved through the Ammo property mapping setup through the Demo Agent component. If this amount is less than the constant then the Int Comparison task will return success and the branch will execute. If the agent is low on ammo then it will stop aiming through the Start Stop Ability task. This is a task created for the Ultimate Character Controller and it will start or stop an ability based on the values specified. In this case the task will stop the Aim ability because the character shouldn't aim when retrieving ammo. Another Start Stop Ability task is run and this task will start the Speed Change task so the character will start running towards the ammo location. The Seek task (from the [Movement Pack](/assets/behavior-designer-movement-pack/)) will use Unity's navigation mesh to move the character to the specified position. After the character has arrived at the position the Start Stop Ability task is executed again only this time it will stop the Speed Change ability so the character will stop running.

> Image unavailable in the source documentation: `UltimateCharacterControllerTreeCanSeeBranch-1024x736.png`

If the agent doesn't need ammo then the next highest priority branch is the Can See branch. This branch contains the main action in that it will actually attack the player when the player is within sight. Similar to the Ammo branch, the can see branch uses a Lower Priority Conditional Abort so it will abort any lower priority branch. The Can See branch will be able to abort any branches to the right of it, which means that it will not be able to abort the Ammo branch because the Ammo branch is to the left of the Can See branch. The first task within the Can See branch is the Can See Object task from the Movement Pack. Can See Object will use a layer mask to search for any objects within sight. The player is on the Character layer so the task will only search for objects that are on that layer. Once the task finds the player the Is Alive task executes which will determine if the player is alive. There's no need to attack a dead character. The Set Shared GameObject task is then a helper task that will transfer the found Can See Object value to the Target variable. This is done so when other tasks operate on the found player variable the original object isn't lost. Two Set Bool tasks are then executed which indicates that the agent should wander if the player is lost and that the target's position should be updated. The right branch under the original Parallel task will then set the target's position to the Last Position variable.

![](https://opsive.com/wp-content/uploads/2018/04/UltimateCharacterControllerTreeCanSeeAttackMovementBranch-1024x637.png)

A Selector task is then run which will first evaluate the left branch. The goal of the left branch is to attack the target for as long as the target is in sight. To accomplish this a Sequence task is used with the Self Conditional Abort. The Self Conditional Abort is a new abort type and this abort type will reevaluate the Conditional task for as long as the current branch is active. In this case the current branch contains the Is Alive task along with a Selector so it will reevaluate Is Alive for as long as the agent can see the target. The Is Alive task will return failure when the target is no longer alive.

![](https://opsive.com/wp-content/uploads/2018/04/UltimateCharacterControllerTreeCanSeeAttackMovementParallelBranch-1024x514.png)

The first branch that the Selector task will evaluate has a Parallel task as the parent. This Parallel task runs two branches:

-   The left branch attacks if the target is within sight
-   The right branch will keep the agent near the target

![](https://opsive.com/wp-content/uploads/2018/04/UltimateCharacterControllerTreeCanSeeAttackMovementAttackBranch.png)

The left Attack branch uses another Can See Object task to determine if the agent is near the target. This Can See Object task is different from the first Can See Object task as it has a smaller distance magnitude so the agent will only attack when near the target. If the target is near the Start Stop Ability task will execute to keep the character aiming. After the agent is aiming the Start Stop Use task will execute which will actually use the item, which will either fire the assault rifle or swing the sword. A Wait task is then used to prevent the agent from trying to attack every frame.

![](https://opsive.com/wp-content/uploads/2018/04/UltimateCharacterControllerTreeCanSeeAttackMovementMovementBranch-1024x524.png)

While the Attack branch is running the Move Towards branch will also run. This branch contains two parts:

-   Move into position after first acquiring the target.
-   Stay in position after arriving in position.

![](https://opsive.com/wp-content/uploads/2018/04/UltimateCharacterControllerTreeCanSeeAttackMovementInitialMovementBranch.png)

To move into position the Within Distance task is used to determine if the agent is within distance of the target. A Self Conditional Abort is used so the Within Distance task will reevaluate for as long as any tasks within the current branch are active, in this case it will be the Seek task. As soon as Seek moves the agent close to the target the Within Distance task will return success and the Inverter will change that success to a failure so the branch will then stop executing. While the Seek task is active the Speed Change ability will be activated so the agent will run towards the target.

![](https://opsive.com/wp-content/uploads/2018/04/UltimateCharacterControllerTreeCanSeeAttackMovementStayMovementBranch-1024x546.png)

After the agent has move to be within distance of the target the right branch will keep the agent near the target. There are three main differences between this branch and the previous Move Towards branch:

-   The current branch will have the character walk instead of run while seeking the target.
-   A Can See Object task is used in addition to Within Distance so the agent will always be in sight of the target while attacking. As an example the target may move inside a structure which would cause prevent the agent from seeing the target even though the target may still be near the agent.
-   An Idle task is used if the agent doesn't need to seek into any position. If the target is standing still and is within sight then the agent can keep attacking without having to change positions.

![](https://opsive.com/wp-content/uploads/2018/04/UltimateCharacterControllerTreeCanSeeMovementResetBranch.png)

The agent will now attack and move towards the target while within distance. If the target gets away from the agent and moves too far away then the right Move Towards branch will return failure and execute the Reset branch. This Reset branch runs two Actions which will ensure the agent is no longer attacking and is no longer aiming.

![](https://opsive.com/wp-content/uploads/2018/04/UltimateCharacterControllerTreeCanSeeTargetDeathBranch.png)

When the target was first acquired the Wander and Update Position variables were set so the agent will search for the target if the target is lost. If the target is killed by the agent then there is no need for the agent to wander so the Target Death branch will reset all of the attacking related variables back to the default.

![](https://opsive.com/wp-content/uploads/2018/04/UltimateCharacterControllerTreeTakeDamageBranch-1024x342.png)

If the agent doesn't need to get ammo and the player is not within sight then the next highest priority branch will run. This branch uses the Ultimate Character Controller's event system to determine if the agent has taken damage. If the agent has taken damage then the Has Taken Damage task will return success and the branch will execute. When the agent has taken damage the branch will first get the position of the object that it took damage from and set Wander to true. Before the agent moves towards the target it will first determine if their health is critically low. If the health is critically low then the agent will seek towards a health pack. After the agent has either retrieved a health pack or determines that more health is not needed the branch will end. Remember that the Wander variable was set to true so the Wander branch will start executing if there are no more higher priority branches.

![](https://opsive.com/wp-content/uploads/2018/04/UltimateCharacterControllerTreeCanHearBranch.png)

The next highest priority branch is the Can Hear branch. This branch uses the Can Hear Object task from the Movement Pack to determine if any audio sources are emitted a sound. If any audio is heard then the agent will run towards the audio source position by starting the Speed Change task and using the Seek task to move into position. The Wander variable is also set to true so the agent will wander if the target can't be seen by the time the agent arrives at the Seek location.

![](https://opsive.com/wp-content/uploads/2018/04/UltimateCharacterControllerTreeWanderBranch-1024x239.png)

Throughout the execution of the tree there have been multiple cases where the Wander task was set to true. The Bool Comparison task will compare this Wander task variable to true to determine if the agent should wander. Before the agent can wander they first have to Seek to the Last Position. This variable will be set whenever the Update Position variable is true and it will indicate the last position that the target was located. When the agent arrives at the Last Position the Wander task will then execute which allows the agent to search for the target. Remember that during this time the higher priority branches are being reevaluted so if the player comes within sight of the agent at any time then the Can See branch will abort the current branch so the character can start to attack. The Wander task is parented to the Parallel Selector task which will execute all children until a child returns success. To the right of the Wander task is the Wait task which will return success after a predetermined duration. This will prevent the agent from wandering forever and put a cap to the amount of time that the agent wanders.

![](https://opsive.com/wp-content/uploads/2018/04/UltimateCharacterControllerTreePatrolBranch.png)

If no other branches need to execute then the tree will fall back to the Patrol branch. This branch will move the character between patrol points and keep the character moving until a higher priority branch aborts it.

![](https://opsive.com/wp-content/uploads/2018/04/UltimateCharacterControllerTreeUpdatePositionBranch.png)

As the Ammo, Can See, Taken Damage, Can Hear, Wander, and Patrol branches are executed near the top of the tree the Update Position branch will also execute. This branch will update the position of the target when the Update Position is true. This branch is separated out from the rest of the tree because not just a single branch can set Update Position to true so to prevent having to add the same tasks multiple times this branch has been added near the top under a Parallel task. Now that you've completed this overview you should have enough knowledge to get started to create you own tree with the Ultimate Character Controller. Make sure you go through the demo tree a few times to get familiar with Behavior Designer's visual editor.

---

<a id="page-behavior-designer-integrations-playmaker"></a>

# Playmaker

[View this page online](https://opsive.com/support/documentation/behavior-designer/integrations/playmaker/)

[Playmaker](https://assetstore.unity.com/packages/tools/visual-scripting/playmaker-368?aid=1100lGdc) is a popular visual scripting tool which allows you to easily create finite state machines. Behavior Designer integrates directly with PlayMaker by allowing PlayMaker to carry out the action or conditional tasks and then resume the behavior tree from where it left off. PlayMaker integration files are located on the [downloads page](/downloads) because Playmaker is not required for Behavior Designer to work. To get started, first make sure you have Playmaker installed and have imported the integration package. Once those files are imported you are ready to start creating behavior trees with Playmaker. To get started, create a very basic tree with a sequence task who has two Start FSM child tasks:

![](https://opsive.com/wp-content/uploads/2018/04/PlaymakerBehaviorTreeStart.png)

Next add two Playmaker FSM components to the same game object that you added the behavior tree to.

![](https://opsive.com/wp-content/uploads/2018/04/PlaymakerComponents.png)

Open Playmaker and start creating a new FSM. This FSM is going to be a simple FSM to show how Behavior Designer interacts with Playmaker. For a more complicated FSM take a look at the Playmaker sample project. Behavior Designer starts the Playmaker FSM by sending it an event. Create this event by adding a new state called "Behavior Tree Listener" and adding a new global event called "StartFSM". The event must be global otherwise Behavior Designer will never be able to start the FSM.

![](https://opsive.com/wp-content/uploads/2018/04/PlaymakerEvent.png)

Add a transition from that event along with a wait state, a set bool state, and a resume behavior tree state. Make sure you transition from the Resume Behavior Tree state to the Behavior Tree Listener state so the FSM can be started again from Behavior Designer.

![](https://opsive.com/wp-content/uploads/2018/04/PlaymakerStates.png)

Create a new variable within the Set Bool state and set that value to true.

![](https://opsive.com/wp-content/uploads/2018/04/PlaymakerSetBool.png)

Then within the Resume Behavior Tree state we want to return success based off of that bool value:

![](https://opsive.com/wp-content/uploads/2018/04/PlaymakerReturnBool.png)

That's it for this FSM. Create the same states and variables for the second FSM that we created earlier. Do not set the bool variable to true for this FSM.

![](https://opsive.com/wp-content/uploads/2018/04/PlaymakerStates2.png)

We are now done working in Playmaker. Open your behavior tree back up within Behavior Designer. Select the left Playmaker task and start assigning the values to the variables. Playmaker Game Object is assigned to the game object that we added the Playmaker FSM components to. FSM Name is the name of the Playmaker FSM. Event name is the name of the global event that we created within Playmaker.

![](https://opsive.com/wp-content/uploads/2018/04/PlaymakerBehaviorDesigner.png)

Now we need to assign the values for the right Playmaker task. The values should be the same as the left Playmaker task except a different FSM Name.

![](https://opsive.com/wp-content/uploads/2018/04/PlaymakerBehaviorDesigner2.png)

That's it! When you hit play you'll see the first Playmaker task run for a second and then the second Playmaker task will start running.

![](https://opsive.com/wp-content/uploads/2018/04/PlaymakerRunning.png)

If you were to swap the tasks so the second Playmaker task runs before the first Playmaker FSM, the behavior tree will never get to the first Playmaker FSM because the second Playmaker FSM returned failure and the sequence task stopped executing its children.

---

<a id="page-behavior-designer-integrations-uscript"></a>

# uScript

[View this page online](https://opsive.com/support/documentation/behavior-designer/integrations/uscript/)

[uScript](https://assetstore.unity.com/packages/tools/visual-scripting/uscript-professional-1808?aid=1100lGdc) is a visual scripting tool which allows you to create complicated setups without needing to write a single line of code. Behavior Designer integrates directly with uScript by allowing uScript to carry out the action or conditional tasks and then resume the behavior tree from where it left off. uScript integration files are located on the [downloads page](/downloads) because uScript is not required for Behavior Designer to work. To get started, first make sure you have uScript installed and have imported the integration package. Once those files are imported you are ready to start creating behavior trees with uScript . To get started, create a very basic tree with a sequence task who has two Start Graph child tasks:

![](https://opsive.com/wp-content/uploads/2018/04/uScriptBehaviorTree.png)

Now we need to create two GameObjects which will hold the compiled uScript graph:

![](https://opsive.com/wp-content/uploads/2018/04/uScriptHierarchy.png)

Open uScript and start creating a new graph. Add the Behavior Tree Signal node, located under Events/Signals. When Behavior Designer wants to start executing a uScript graph it will start from this node. This node contains four events: Start Signal, Pause Signal, Resume Signal, and End Signal. Start Signal is used when the behavior tree task starts running. Pause Signal gets called when the behavior tree is paused, and the Resume Signal gets called when the behavior tree resumes from being paused. Finally, End Signal gets called when the uScript task ends. For our graph we are only going to create a few nodes, the uScript sample project shows a more complicated uScript graph. Create a node which has a delay of 3 seconds, sets a bool, then resumes the behavior tree. The Resume Behavior Tree node is located under Actions/Behavior Designer:

![](https://opsive.com/wp-content/uploads/2018/04/uScriptBasicGraph.png)

Now we need to create a Owner GameObject and bool variable.

![](https://opsive.com/wp-content/uploads/2018/04/uScriptGraphVariables.png)

Save the uScript graph and assign the component to your first uScript graph GameObject. Answer no if uScript asks if you want to assign the component to the master GameObject.

![](https://opsive.com/wp-content/uploads/2018/04/uScriptGraphComponent.png)

Create one more uScript graph. Make it the same as the last graph except set the bool to false:

![](https://opsive.com/wp-content/uploads/2018/04/uScriptGraphVariables2.png)

Finally save that graph and assign the component to the second uScript GameObject:

![](https://opsive.com/wp-content/uploads/2018/04/uScriptGraphComponent2.png)

We're almost done. The only thing left to do is to assign the correct uScript GameObject to the tasks within Behavior Designer. Open your behavior tree within Behavior Designer again. Click on the left uScript task and assign the uScript GameObject to your first uScript graph GameObject.

![](https://opsive.com/wp-content/uploads/2018/04/uScriptGraphAssign.png)

Do the same for the right uScript task, only assign the uScript GameObject to your second uScript graph GameObject. That's it! When you hit play you'll see the first uScript task run for three seconds, followed by the second uScript task.

![](https://opsive.com/wp-content/uploads/2018/04/uScriptRunning.png)

If you were to swap the tasks so the second uScript graph runs before the first uScript graph, the behavior tree will never get to the first uScript graph because the second uScript graph returned failure and the sequence task stopped executing its children.

---

<a id="page-behavior-designer-integrations-visual-scripting"></a>

# Visual Scripting

[View this page online](https://opsive.com/support/documentation/behavior-designer/integrations/visual-scripting/)

Behavior Designer integrates directly with Unity's [Visual Scripting package](https://learn.unity.com/project/introduction-to-visual-scripting) by allowing Visual Scripting to carry out the action tasks and then resume the behavior tree from where it left off. The Visual Scripting integration files are located on the [downloads page](https://opsive.com/downloads). To get started ensure you have first added the BehaviorDesignerExtensions type to the Visual Scripting Type Options. This menu option can be found within the Unity Project Settings dialogue. Be sure to select Regenerate Nodes after you have added the type.

![](https://opsive.com/wp-content/uploads/2023/05/VisualScriptingTypeOptions.png)

After the type has been added your Script Graph can communicate with your behavior tree. Your behavior tree should contain the Start Script Graph task with the name of the event that you want to start with your Script Graph. This event name should be the same as the string within a new Custom Event node from your Script Graph.

![](https://opsive.com/wp-content/uploads/2023/05/ScriptGraphCustomEvent.png)

After your Custom Event has executed you can perform any operations within your Script Graph. In the sample Script Graph the Add node is used to add a constant to the synchronized variable. After all of your operations have been performed you can sync with the behavior tree by using the Resume Behavior Tree node from Behavior Designer Extensions object.

![](https://opsive.com/wp-content/uploads/2023/05/ScriptGraphResumeBehaviorTree.png)

If within the Start Script Graph task you are not waiting on the Behavior Tree to complete then you do not need to add the Resume Behavior Tree node.

---

<a id="page-behavior-designer-videos"></a>

# Videos

[View this page online](https://opsive.com/support/documentation/behavior-designer/videos/)

The following videos will describe how to use Behavior Designer: https://www.youtube.com/watch?v=PuLuwzgYB4g&list=PLCPL5IYZm1NLVVxJx3-CFTLuHvLbCgmzk
