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

Writing Custom State Behaviours

PreviousListening to Events from ScriptNextExtending VSM

Last updated 1 year ago

Was this helpful?

One of the most powerful components coming with Visual State Machine is the StateBehaviour class. It allows you to easily implement the and create custom MonoBehaviours for your different states. This can for example be used to implement state behaviours for AI characters, game states or UI menus.

using Ilumisoft.VisualStateMachine;
using UnityEngine;

/// <summary>
/// Derive from StateBehaviour to execute custom logic when a state is executed.
/// </summary>
public class MenuStateBehaviourExample : StateBehaviour
{
    /// <summary>
    /// The id of the state the behviour should act on
    /// </summary>
    public override string StateID => "Menu";

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

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

    protected override void OnUpdateState()
    {
        // Execute something when the state is updated...
    }
}

To use a custom State Behaviour script, simply add it to a Game Object and assign the State Machine it should be executed on.

State Design Pattern