Visual State Machine
  • Welcome
  • FAQ
  • Get Started
    • Setup
    • How to Create a State Machine
    • How to Open the Graph Editor
    • How to Create a State
    • About State IDs and Renaming States
    • How to Duplicate States
    • How to Set the Entry State
    • How to Create a Transition
    • About Transition IDs and Renaming Transitions
    • About Transition Labels
    • How to Trigger a Transition
    • How to Trigger a Transition by Label
    • How to Listen to Graph Events
  • Advanced
    • Execution Order
    • Listening to Events from Script
    • Writing Custom State Behaviours
    • Extending VSM
Powered by GitBook
On this page

Was this helpful?

  1. Advanced

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}'");
    }
}
PreviousExecution OrderNextWriting Custom State Behaviours

Last updated 2 years ago

Was this helpful?