Accessing Variables

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

using Opsive.GraphDesigner.Runtime.Variables;
using Opsive.StateDesigner.Runtime.Actions;
using Opsive.StateDesigner.Runtime.States;
using UnityEngine;

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

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

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

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

public class AccessVariable : MonoBehaviour
{
    public StateMachine m_StateMachine;

    public void Start()
    {
        SharedVariable<GameObject> target = m_StateMachine.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_StateMachine.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.GraphDesigner.Runtime.Variables;
using Opsive.GraphDesigner.Runtime;
using UnityEngine;

public class AccessVariable : MonoBehaviour
{
    public StateMachine m_StateMachine;
    public GameObjectSharedVariables m_GameObjectSharedVariables;
    public SceneSharedVariables m_SceneSharedVariables;

    public void Start()
    {
        var target = m_StateMachine.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.
    }
}