Listening to Events from Script

Visual State Machine allows you to easily listen to events from script, by accessing states by their ID and add listeners to the different events:

using Ilumisoft.VisualStateMachine;
using UnityEngine;

public class StateCallbackExample : MonoBehaviour
{
    /// <summary>
    /// Reference to the state machine
    /// </summary>
    [SerializeField]
    StateMachine stateMachine;

    /// <summary>
    /// The ID of the state you want to receive callbacks from
    /// </summary>
    [SerializeField]
    string stateID;

    private void Awake()
    {
        if (stateMachine != null)
        {
            // Get the state by it's ID and add listeners to it's enter, exit and update event
            if (stateMachine.Graph.TryGetState(stateID, out var state))
            {
                state.OnEnterState.AddListener(OnEnterState);
                state.OnExitState.AddListener(OnExitState);
                state.OnUpdateState.AddListener(OnUpdateState);
            }
            else
            {
                Debug.Log($"Could not find state with the id '{stateID}'", this);
            }
        }
    }

    private void OnUpdateState()
    {
        // Execute something when the state is updated
    }

    private void OnExitState()
    {
        // Execute something when the state is exited
        Debug.Log($"On Exit State: '{stateID}'");
    }

    private void OnEnterState()
    {
        // Execute something when the state is entered
        Debug.Log($"On Enter State: '{stateID}'");
    }
}

Last updated