Creating custom Context and Nodes

Making a custom context for our behaviors

The badger agent has a BaseContext referencing the agent's GameObject, blackboard, and transform. This context is passed along when executing nodes.

It can be useful to extend the context if you for instance need access to a specific service when building your nodes.

To extend the BaseContext you need to create a new class for the context, the agent, and the agent component.

To create the new context, create a new class and name it MyCustomContext.

public class MyCustomContext : BaseContext
{
}

Create a new agent class that implements the new context class.

public class MyCustomAgent : Agent<MyCustomContext>
{
}

Finally, create a class for the agent component. This class inherits from Monobehaviour and can be attached to a GameObject.

public class MyCustomAgentComponent : AgentComponent<MyCustomAgent>
{
}

You can now assign the "MyCustomAgentComponent" to a GameObject and select a tree in the "Asset" field.

Creating and adding custom nodes

Custom nodes can easily be created and added to the node creation menu. Start by creating a new class for your node.

[NodeMenu("MyCustomNode", "Custom")]
public class MyCustomNode : CustomNode<BaseContext>
{
    protected override State OnExecute(BaseContext context)
    {
        return State.Success;
    }
}

The node inherits from CustomNode which requires a context. This can be the default BaseContext or any that you create yourself.

Every action node has an "OnExecute" function where you can implement some custom behavior. You can take a look at the custom node in the examples for some simple behaviors.

The "NodeMenu" attribute allows us to add the node to the node creation menu, where the first parameter is the name, and the second is the category.

We can also add the special attribute "Expose" to any field or property so that it shows up in the tree view. The "Blackboard" attribute can be added so that we can assign a key from the blackboard asset.

[NodeMenu("MyCustomNode", "Custom")]
public class MyCustomNode : CustomNode<BaseContext>
{
    [Expose] public int value;
    [Blackboard(typeof(int))] public int key;

    protected override State OnExecute(BaseContext context)
    {
        return State.Success;
    }
}

Last updated