Skip to content

Behavior trees for Unity3D projects. Implementation with visual programming

License

Notifications You must be signed in to change notification settings

IpeBT/fluid-behavior-tree-visual

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Visual BT

This section contains information about Visual BT, the project being developed as the code assignment of MAC0332 - Software Engineering

Visual BT is a visual implementation of behavior trees for Unity projects. This is an increment of fluid BT, with the added programmable GUI and some new nodes.

Completed features

  • Intuitive and programmable graphical interface, in the "drag-and-drop" style
  • Node argument editor, which allows access to exposed parameters of the tree node classes
  • Modified SelectorRandom node, making it actually random every time

Expected new features

  • Real-time tree execution visualizer, for debbuging
  • New Interrupt node
  • Shared variables declaration, creating a "global" memory for the tree

Progress tracking

Check out our Kanban on Trello.

How to create a tree in the Graphical Interface

  1. Add the component BTRunner to the object you want to control
  2. Create a new BehaviorTree at your current directory by right-clicking and then selecting Create > ScriptableObjects > BehaviorTree
  3. Drag and drop the new asset into the Tree proprerty of BTRunner
  4. Open the tree editor by clicking on Windows in the top bar and then VisualFLuidBT
  5. Select the tree Scriptable Object by double-clicking it, either on the filesystem or on the runner
  6. Add a root to your tree by right-clicking on the Tree View, then selecting RootNode
  7. Create the tree you want by selecting the nodes on the right-click menu, editing their properties in the left Inspector and then connecting them by creating edges
  8. When you are done hit the Save button below the Inspector View
  9. Run the scene to check your behavior

Creating new nodes from ActionBase

  1. Creating new actions is the same as it was beafore with the original FluidBT. Open the directory where all actions are located, just for the sake of project organization, and create a new script with a new class inheriting from ActionBase
  2. Override the ActionBase methods and create your own node behavior
  3. After recompiling the project, the new custom node option will appear on the right-click menu and can be created like any other node

Screenshots

image

The first image demonstrates how to open the VisualFluidBT window

image

This image shows the path to create a new Behavior Tree asset

VisualFluidBT window

In the image above, we can see an example of a tree with the applied UXML for each type of node

VisualFluidBT window

The image above shows the Behavior Tree in motion during time of execution. We can see that active nodes have a green outline to showcase what portion of the Behavior Tree is currently running.

Implementation of the Graphical Interface

The first step in creating the new Visual and programmable interface for FluidBT was transforming all of its major components into Scriptable Objects. This was necessary because we want the user to be able to edit the tree inside the Editor and then save all the information in an asset, so that it can be loaded and reused at any point.

Then, we chose to use UI Builder to create the new Editor window, where the tree editor and inspector view would be implemented. This tool is part of the UI Toolkit, which is a core feature of Unity game engine since the 2021.1 version.

Furthermore, we have elected to use the experimental API called GraphView to represent the visual elements of the tree structure. The tree itself is a subclass of the graph view and all of its nodes, called Node Views, are subtypes of the corresponding class in the API.

In addition, we created the Inspector View panel, which allows the user to see and edit the public properties of a node, just like in the main Inspector of the Editor. Every time the user clicks on a different node in the Tree View, the Inspector must quickly switch to show the new node's properties.

Finally, we started altering the style sheets of the node views to give them a customized apperance and make them more distintic. This was done by editing the UXML files on the UI Builder tool.

New Nodes

  • True Selector Random: the original SelectorRandom has the standard behavior of randomly choosing one of its children and then executing it, but not changing the selected child until the BehaviorTree resets. Alternatively, the TrueSelectorRandom was created such that it selects a new random child everytime a new behavior flow passes through it.
  • Play Sound: this node plays a chosen sound at a specific location in the Scene. The location of the sound is shows as a parameter that can be freely changed.

Fluid BT

The following section contains information about the original implementation of Fluid BT, with some alterations.

Code driven use

When creating trees via code, you'll need to store them in a variable to properly cache all the necessary data.

using UnityEngine;
using CleverCrow.Fluid.BTs.Tasks;
using CleverCrow.Fluid.BTs.Trees;

public class MyCustomAi : MonoBehaviour {
    [SerializeField]
    private BehaviorTree _tree;
    
    private void Awake () {
        _tree = new BehaviorTreeBuilder(gameObject)
            .Sequence()
                .Condition("Custom Condition", () => {
                    return true;
                })
                .Do("Custom Action", () => {
                    return TaskStatus.Success;
                })
            .End()
            .Build();
    }

    private void Update () {
        // Update our tree every frame
        _tree.Tick();
    }
}

What a Returned TaskStatus Does

Depending on what you return for a task status different things will happen.

  • Success: Node has finished, next tree.Tick() will restart the tree if no other nodes to run
  • Failure: Same as success, except informs that the node failed
  • Continue: Rerun this node the next time tree.Tick() is called. A pointer reference is tracked by the tree and can only be cleared if tree.Reset() is called.

Tree Visualizer

THIS WILL BE OBSOLETE

As long as your tree storage variable is set to public or has a SerializeField attribute. You'll be able to print a visualization of your tree while the game is running in the editor. Note that you cannot view trees while the game is not running. As the tree has to be built in order to be visualized.

Visualizer

Extending Trees via code

You can safely add new code to your behavior trees with several lines. Allowing you to customize BTs while supporting future version upgrades.

using UnityEngine;
using CleverCrow.Fluid.BTs.Tasks;
using CleverCrow.Fluid.BTs.Tasks.Actions;
using CleverCrow.Fluid.BTs.Trees;

public class CustomAction : ActionBase {
    protected override TaskStatus OnUpdate () {
        Debug.Log(Owner.name);
        return TaskStatus.Success;
    }
}

public static class BehaviorTreeBuilderExtensions {
    public static BehaviorTreeBuilder CustomAction (this BehaviorTreeBuilder builder, string name = "My Action") {
        return builder.AddNode(new CustomAction { Name = name });
    }
}

public class ExampleUsage : MonoBehaviour {
    public void Awake () {
        var bt = new BehaviorTreeBuilder(gameObject)
            .Sequence()
                .CustomAction()
            .End();
    }
}

Installing

Visual Behavior Tree is used through Unity's Package Manager. In order to use it you'll need to add the following lines to your Packages/manifest.json file. After that you'll be able to visually control what specific version of Visual BT you're using from the package manager window in Unity. This has to be done so your Unity editor can connect to NPM's package registry.

{
  "scopedRegistries": [
    {
      "name": "NPM",
      "url": "https://registry.npmjs.org",
      "scopes": [
        "com.fluid"
      ]
    }
  ],
  "dependencies": {
    "com.fluid.behavior-tree": "2.2.0"
  }
}

Archives of specific versions and release notes are available on the releases page.

Example Scene

You might want to look at the capture the flag example project for a working example of how Visual Behavior Tree can be used in your project. It demonstrates real time usage with units who attempt to capture the flag while grabbing power ups to try and gain the upper hand.

Table of Contents

Example Scene

You might want to look at the capture the flag example project for a working example of how Visual Behavior Tree can be used in your project. It demonstrates real time usage with units who attempt to capture the flag while grabbing power ups to try and gain the upper hand.

Library

Visual Behavior Tree comes with a robust library of pre-made actions, conditions, composites, and other nodes to help speed up your development process.

Actions

Action Generic

You can create a generic action on the fly. If you find yourself re-using the same actions you might want to look into the section on writing your own custom actions.

.Sequence()
    .Do("Custom Action", () => {
        return TaskStatus.Success;
    })
.End()

Wait

Skip a number of ticks on the behavior tree.

.Sequence()
    // Wait for 1 tick on the tree before continuing
    .Wait(1)
    .Do(MyAction)
.End()

Wait Time

Waits until the passed number of seconds have expired in deltaTime.

.Sequence()
    .WaitTime(2.5f)
    .Do(MyAction)
.End()

Conditions

Condition Generic

You can create a generic condition on the fly. If you find yourself re-using the same actions you might want to look into the section on writing your own custom conditions.

.Sequence()
    .Condition("Custom Condtion", () => {
        return true;
    })
    .Do(MyAction)
.End()

RandomChance

Randomly evaluate a node as true or false based upon the passed chance.

.Sequence()
    // 50% chance this will return success
    .RandomChance(1, 2)
    .Do(MyAction)
.End()

Composites

Sequence

Runs each child node in order and expects a Success status to tick the next node. If Failure is returned, the sequence will stop executing child nodes and return Failure to the parent.

NOTE It's important that every composite is followed by a .End() statement. This makes sure that your nodes are properly nested when the tree is built.

.Sequence()
    .Do(() => { return TaskStatus.Success; })
    .Do(() => { return TaskStatus.Success; })
    
    // All tasks after this will not run and the sequence will exit
    .Do(() => { return TaskStatus.Failure; })

    .Do(() => { return TaskStatus.Success; })
.End()

Selector

Runs each child node until Success is returned.

.Selector()
    // Runs but fails
    .Do(() => { return TaskStatus.Failure; })

    // Will stop here since the node returns success
    .Do(() => { return TaskStatus.Success; })
    
    // Does not run
    .Do(() => { return TaskStatus.Success; })
.End()

SelectorRandom

Randomly selects a child node with a shuffle algorithm. Looks until Success is returned or every node fails. Shuffles every time the tree initially start running it.

.SelectorRandom()
    .Do(() => { return TaskStatus.Failure; })
    .Do(() => { return TaskStatus.Success; })
    .Do(() => { return TaskStatus.Failure; })
.End()

Parallel

Runs all child nodes at the same time until they all return Success. Exits and stops all running nodes if ANY of them return Failure.

.Parallel()
    // Both of these tasks will run every frame
    .Do(() => { return TaskStatus.Continue; })
    .Do(() => { return TaskStatus.Continue; })
.End()

Decorators

Decorators are parent elements that wrap any node to change the return value (or execute special logic). They are extremely powerful and a great compliment to actions, conditions, and composites.

Decorator Generic

You can wrap any node with your own custom decorator code. This allows you to customize re-usable functionality.

NOTE: You must manually call Update() on the child node or it will not fire. Also every decorator must be followed by a .End() statement. Otherwise the tree will not build correctly.

.Sequence()
    .Decorator("Return Success", child => {
        child.Update();
        return TaskStatus.Success;
    })
        .Do(() => { return TaskStatus.Failure; })
    .End()
    .Do(() => { return TaskStatus.Success; })
.End()

Inverter

Reverse the returned status of the child node if it's TaskStatus.Success or TaskStatus.Failure. Does not change TaskStatus.Continue.

.Sequence()
    .Inverter()
        .Do(() => { return TaskStatus.Success; })
    .End()
.End()

ReturnSuccess

Return TaskStatus.Success if the child returns TaskStatus.Failure. Does not change TaskStatus.Continue.

.Sequence()
    .ReturnSuccess()
        .Do(() => { return TaskStatus.Failure; })
    .End()
.End()

ReturnFailure

Return TaskStatus.Failure if the child returns TaskStatus.Success. Does not change TaskStatus.Continue.

.Sequence()
    .ReturnFailure()
        .Do(() => { return TaskStatus.Success; })
    .End()
.End()

RepeatForever

Return TaskStatus.Continue regardless of what status the child returns. This decorator (and all descendent tasks) can be interrupted by calling BehaviorTree.Reset().

.Sequence()
    .RepeatForever()
        .Do(() => { return TaskStatus.Success; })
    .End()
.End()

RepeatUntilFailure

Return TaskStatus.Failure if the child returns TaskStatus.Failure, otherwise it returns TaskStatus.Continue.

.Sequence()
    .RepeatUntilFailure()
        .Do(() => { return TaskStatus.Success; })
    .End()
.End()

RepeatUntilSuccess

Return TaskStatus.Success if the child returns TaskStatus.Success, otherwise it returns TaskStatus.Continue.

.Sequence()
    .RepeatUntilSuccess()
        .Do(() => { return TaskStatus.Success; })
    .End()
.End()

Creating Reusable Behavior Trees

Trees can be combined with just a few line of code. This allows you to create injectable behavior trees that bundles different nodes for complex functionality such as searching or attacking.

Be warned that spliced trees require a newly built tree for injection, as nodes are only deep copied on .Build().

using CleverCrow.Fluid.BTs.Trees;
using CleverCrow.Fluid.BTs.Tasks;
using UnityEngine;

public class MyCustomAi : MonoBehaviour {
    private BehaviorTree _tree;
    
    private void Awake () {
        var injectTree = new BehaviorTreeBuilder(gameObject)
            .Sequence()
                .Do("Custom Action", () => {
                    return TaskStatus.Success;
                })
            .End();

        _tree = new BehaviorTreeBuilder(gameObject)
            .Sequence()
                .Splice(injectTree.Build())
                .Do("Custom Action", () => {
                    return TaskStatus.Success;
                })
            .End()
            .Build();
    }

    private void Update () {
        // Update our tree every frame
        _tree.Tick();
    }
}

Creating Custom Reusable Nodes

What makes Visual Behavior Tree so powerful is the ability to write your own nodes and add them to the builder without editing any source. You can even create Unity packages that add new builder functionality. For example we can write a new tree builder method like this that sets the target of your AI system with just a few lines of code.

var tree = new BehaviorTreeBuilder(gameObject)
    .Sequence()
        .AgentDestination("Find Enemy", target)
        .Do(() => {
            // Activate chase enemy code
            return TaskStatus.Success; 
        })
    .End()
    .Build();

Your First Custom Node and Extension

It should take about 3 minutes to create your first custom action and implement it. First create a new action.

using CleverCrow.Fluid.BTs.Tasks;
using CleverCrow.Fluid.BTs.Tasks.Actions;
using UnityEngine;
using UnityEngine.AI;

public class AgentDestination : ActionBase {
    private NavMeshAgent _agent;
    public Transform target;

    protected override void OnInit () {
        _agent = Owner.GetComponent<NavMeshAgent>();
    }

    protected override TaskStatus OnUpdate () {
        _agent.SetDestination(target.position);
        return TaskStatus.Success;
    }
}

Next we need to extend the BehaviorTreeBuilder script with our new AgentDestination action. For more information on C# class extensions see the official docs.

using CleverCrow.Fluid.BTs.Trees;

public static class BehaviorTreeBuilderExtensions {
    public static BehaviorTreeBuilder AgentDestination (this BehaviorTreeBuilder builder, string name, Transform target) {
        return builder.AddNode(new AgentDestination {
            Name = name,
            target = target,
        });
    }
}

And you're done! You've now created a custom action and extendable behavior tree builder that's future proofed for new versions. The following examples will be more of the same. But each covers a different node type.

Custom Actions

You can create your own custom actions with the following template. This is useful for bundling up code that you're using constantly.

using UnityEngine;
using CleverCrow.Fluid.BTs.Tasks;
using CleverCrow.Fluid.BTs.Tasks.Actions;

public class CustomAction : ActionBase {
    // Triggers only the first time this node is run (great for caching data)
    protected override void OnInit () {
    }

    // Triggers every time this node starts running. Does not trigger if TaskStatus.Continue was last returned by this node
    protected override void OnStart () {
    }

    // Triggers every time `Tick()` is called on the tree and this node is run
    protected override TaskStatus OnUpdate () {
        // Points to the GameObject of whoever owns the behavior tree
        Debug.Log(Owner.name);
        return TaskStatus.Success;
    }

    // Triggers whenever this node exits after running
    protected override void OnExit () {
    }
}

Add your new node to an extension.

using CleverCrow.Fluid.BTs.Trees;

public static class BehaviorTreeBuilderExtensions {
    public static BehaviorTreeBuilder CustomAction (this BehaviorTreeBuilder builder, string name = "My Action") {
        return builder.AddNode(new CustomAction {
            Name = name,
        });
    }
}

Custom Conditions

Custom conditions can be added with the following example template. You'll want to use these for checks such as sight, if the AI can move to a location, and other tasks that require a complex check.

using UnityEngine;
using CleverCrow.Fluid.BTs.Tasks;

public class CustomCondition : ConditionBase {
    // Triggers only the first time this node is run (great for caching data)
    protected override void OnInit () {
    }

    // Triggers every time this node starts running. Does not trigger if TaskStatus.Continue was last returned by this node
    protected override void OnStart () {
    }

    // Triggers every time `Tick()` is called on the tree and this node is run
    protected override bool OnUpdate () {
        // Points to the GameObject of whoever owns the behavior tree
        Debug.Log(Owner.name);
        return true;
    }

    // Triggers whenever this node exits after running
    protected override void OnExit () {
    }
}

Add the new condition to your behavior tree builder with the following snippet.

using CleverCrow.Fluid.BTs.Trees;

public static class BehaviorTreeBuilderExtensions {
    public static BehaviorTreeBuilder CustomCondition (this BehaviorTreeBuilder builder, string name = "My Condition") {
        return builder.AddNode(new CustomCondition {
            Name = name,
        });
    }
}

Custom Composites

Visual Behavior Tree isn't limited to just custom actions and conditions. You can create new composite types with a fairly simple API. Here is an example of a basic sequence.

using CleverCrow.Fluid.BTs.TaskParents.Composites;
using CleverCrow.Fluid.BTs.Tasks;

public class CustomSequence : CompositeBase {
    protected override TaskStatus OnUpdate () {            
        for (var i = ChildIndex; i < Children.Count; i++) {
            var child = Children[ChildIndex];

            var status = child.Update();
            if (status != TaskStatus.Success) {
                return status;
            }

            ChildIndex++;
        }

        return TaskStatus.Success;
    }
}

Adding custom composites to your behavior tree is just as simple as adding actions. Just takes one line of code.

using CleverCrow.Fluid.BTs.Trees;

public static class BehaviorTreeBuilderExtensions {
    public static BehaviorTreeBuilder CustomSequence (this BehaviorTreeBuilder builder, string name = "My Sequence") {
        return builder.ParentTask<CustomSequence>(name);
    }
}

Custom Decorators

Decorators can also be custom written to cut down on repetitive code.

using CleverCrow.Fluid.BTs.Decorators;
using CleverCrow.Fluid.BTs.Tasks;

public class CustomInverter : DecoratorBase {
    protected override TaskStatus OnUpdate () {
        if (Child == null) {
            return TaskStatus.Success;
        }

        var childStatus = Child.Update();
        var status = childStatus;

        switch (childStatus) {
            case TaskStatus.Success:
                status = TaskStatus.Failure;
                break;
            case TaskStatus.Failure:
                status = TaskStatus.Success;
                break;
        }

        return status;
    }
}

Implementing decorators is similar to composites. If you need to set arguments on the composite you'll want to take a loot at the method BehaviorTreeBuilder.AddNodeWithPointer().

using CleverCrow.Fluid.BTs.Trees;

public static class BehaviorTreeBuilderExtensions {
    public static BehaviorTreeBuilder CustomInverter (this BehaviorTreeBuilder builder, string name = "My Inverter") {
        // See BehaviorTreeBuilder.AddNodeWithPointer() if you need to set custom composite data from arguments
        return builder.ParentTask<CustomInverter>(name);
    }
}

Nightly Builds

To access nightly builds of develop that are package manager friendly you'll need to manually edit your Packages/manifest.json as so.

{
    "dependencies": {
      "com.fluid.behavior-tree": "https://github.com/ashblue/fluid-behavior-tree.git#nightly"
    }
}

Note that to get a newer nightly build you must delete this line and any related lock data in the manifest, let Unity rebuild, then add it back. As Unity locks the commit hash for Git urls as packages.

Development Environment

If you wish to run to run the development environment you'll need to install node.js. Then run the following from the root once.

npm install

If you wish to create a build run npm run build from the root and it will populate the dist folder.

Making Commits

All commits should be made using Commitizen (which is automatically installed when running npm install). Commits are automatically compiled to version numbers on release so this is very important. PRs that don't have Commitizen based commits will be rejected.

To make a commit type the following into a terminal from the root

npm run commit

Pull Requests / Contributing

Please see the Contributing Guidelines document for more info.

Contributor Credits

Visual BT

André Gustavo Nakagomi Lopez
André Gustavo Nakagomi Lopez

💻
Gabriel da Silva Alves
Gabriel da Silva Alves

💻
Johnny da Silva Lima
Johnny da Silva Lima

💻
Lincoln Yuji de Oliveira
Lincoln Yuji de Oliveira

💻
Mateus Santos Freire
Mateus Santos Freire

💻
Murilo André Gomes Felipe
Murilo André Gomes Felipe

💻
Rodrigo Volpe Battistin
Rodrigo Volpe Battistin

💻

Fluid BT

Thanks goes to these wonderful people (emoji key):

Ash Blue
Ash Blue

💻
Jesse Talavera-Greenberg
Jesse Talavera-Greenberg

💻
PureSaltProductions
PureSaltProductions

📓
Martin Duvergey
Martin Duvergey

🐛
call-stack
call-stack

🐛
Piotr Jastrzebski
Piotr Jastrzebski

💻
Sounghoo
Sounghoo

💻
TNThomas
TNThomas

🐛 💻

This project follows the all-contributors specification. Contributions of any kind welcome!

Contributors ✨

Thanks goes to these wonderful people (emoji key):

This project follows the all-contributors specification. Contributions of any kind welcome!

About

Behavior trees for Unity3D projects. Implementation with visual programming

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • C# 99.6%
  • Other 0.4%