Accessing Variables from non-Task Objects

A MonoBehaviour or another runtime system can read and update Behavior Designer
variables through the owning BehaviorTree.

Get or set a local variable

GetVariable returns the SharedVariable object. Cast it to the matching type
when you need to keep a reference; use SetVariableValue when you only need to
replace its value.

using BehaviorDesigner.Runtime;
using UnityEngine;

public class AgentHealth : MonoBehaviour
{
    [SerializeField] private BehaviorTree behaviorTree;

    public void SetHealth(int health)
    {
        behaviorTree.SetVariableValue("Health", health);
    }

    public int GetHealth()
    {
        var health = behaviorTree.GetVariable("Health") as SharedInt;
        return health?.Value ?? 0;
    }
}

Create Health in the Variables panel before Play Mode if task fields should
reference it. For an existing compatible variable, SetVariable preserves the
original SharedVariable instance and copies the supplied value or property
mapping into it. A mismatched type logs an error. For a new name, it creates a
new instance and copies the data; it does not store the supplied object itself.
Use SetVariableValue for an ordinary value update, and do not rely on
SetVariable replacing references held by tasks.

Use behaviorTree.GetAllVariables() when tooling needs to enumerate a tree’s
variables.

Access a global variable

Global variables expose the same operations through GlobalVariables.Instance:

var alert = GlobalVariables.Instance.GetVariable("Alert") as SharedBool;
if (alert != null) {
    alert.Value = true;
}

GlobalVariables.Instance.SetVariableValue("Alert", true);

Troubleshooting

  • GetVariable returns null: check the name and capitalization and confirm
    you are querying the correct Behavior Tree.
  • The value changes but a task ignores it: confirm the task field is bound
    to the named shared variable rather than using a constant value.
  • A global lookup fails: create and save the variable in Tools > Behavior
    Designer > Global Variables
    before running the scene.