Read and write a value inside a task

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 Shared Variable in the Task Inspector, the Value is shared across those tasks.

Access a graph variable from a component

Variables 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 example above, the component gets the variable named Target and changes it through the SharedVariable.Value property.

Select a variable scope

By default, GetVariable returns the variable that belongs to the graph. To get a variable from a different scope, 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.
    }
}