Accessing Variables

Variables can be access both within the task and within your own script outside of Behavior Designer. In order to get and set the variable value within a task you can use the Value property. As an example:

using Opsive.BehaviorDesigner.Runtime.Tasks;
using Opsive.BehaviorDesigner.Runtime.Tasks.Conditionals;
using Opsive.GraphDesigner.Runtime.Variables;
using UnityEngine;

public class WithinDistance : Conditional
{
    [Tooltip("The object that the agent is searching for.")]
    [SerializeField] protected SharedVariable<GameObject> m_Target;

    public override TaskStatus OnUpdate()
    {
        GameObject targetGameObject = m_Target.Value;
        if (targetGameObject == null) {
            m_Target.Value = GameObject.Find("Player");
        }

As long as the tasks are assigned to the same SharedVariable name within the inspector the Value will be the same reference across tasks. Variable can also be accessed by your own scripts by getting a reference to the BehaviorTree component:

using Opsive.BehaviorDesigner.Runtime;
using Opsive.GraphDesigner.Runtime.Variables;
using UnityEngine;

public class AccessVariable : MonoBehaviour
{
    public BehaviorTree m_BehaviorTree;

    public void Start()
    {
        SharedVariable<GameObject> target = m_BehaviorTree.GetVariable<GameObject>("Target");
        target.Value = gameObject;
    }
}

In the above example we are getting a reference to the variable named “Target”. From there you can get and set the value of the variable with the SharedVariable.Value property. By default GetVariable will return the variable that belongs to the graph. If you want to get a variable of a different scope you can add a second parameter:

SharedVariable target = m_BehaviorTree.GetVariable("Target", SharedVariable.SharingScope.Scene);

The second SharingScope parameter is a convenient way to access variables of all of the scopes, but you can also get a reference to the GameObjectSharedVariables, SceneSharedVariables, or ProjectSharedVariables:

using Opsive.BehaviorDesigner.Runtime;
using Opsive.GraphDesigner.Runtime.Variables;
using UnityEngine;

public class AccessVariable : MonoBehaviour
{
    public BehaviorTree m_BehaviorTree;
    public GameObjectSharedVariables m_GameObjectSharedVariables;
    public SceneSharedVariables m_SceneSharedVariables;

    public void Start()
    {
        var target = m_BehaviorTree.GetVariable<GameObject>("Target"); // Graph Scope.
        target = m_GameObjectSharedVariables.GetVariable<GameObject>("Target"); // GameObject Scope.
        target = m_SceneSharedVariables.GetVariable<GameObject>("Target"); // Scene Scope.
        target = ProjectSharedVariables.Instance.GetVariable<GameObject>("Target"); // Project Scope.
    }
}