Accessing Variables from non-Task Objects
Variables are normally referenced by assigning 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:
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:
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:
GlobalVariables.Instance.GetVariable("MyVariable"); GlobalVariables.Instance.SetVariable("MyVariable", value);