Writing Custom State Behaviours

One of the most powerful components coming with Visual State Machine is the StateBehaviour class. It allows you to easily implement the State Design Patternarrow-up-right 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.

Last updated

Was this helpful?