Extending VSM

The following two examples demonstrate how you could use the callbacks provided by the State Machine class to easily extend the package and implement custom functionality.

Previous State Cache Example

The following component automatically caches the previously active state of the assigned state machine and allows to enter it. This could for example be used to implement an "Undo last turn" feature. You could even further extend this script by implementing a stack to cache a set of previous states.

using Ilumisoft.VisualStateMachine;
using UnityEngine;

/// <summary>
/// Caches the id of the previous state, when the state machine switches states and provides a method to
/// enter it.
/// </summary>
public class PreviousStateCacheExample : MonoBehaviour
{
    [SerializeField]
    StateMachine stateMachine;

    string previousStateID = string.Empty;

    private void Awake()
    {
        if(stateMachine != null)
        {
            stateMachine.OnExitState += OnExitState;
        }
        else
        {
            Debug.LogWarning("No state machine assigned.", this);
        }
    }

    private void OnExitState(State state)
    {
        previousStateID = state.ID;
    }

    public void EnterPreviousState()
    {
        if (stateMachine != null)
        {
            stateMachine.TriggerByState(previousStateID);
        }
    }
}

State Machine Logger

The following component automatically logs which states are entered or exit by the assigned state machine, allowing you to easily identify problems.

using Ilumisoft.VisualStateMachine;
using UnityEngine;

/// <summary>
/// Logs the actions performed by a state machine
/// </summary>
public class StateMachineLogger : MonoBehaviour
{
    [SerializeField]
    StateMachine stateMachine;

    private void Awake()
    {
        if(stateMachine != null)
        {
            stateMachine.OnEnterState += OnEnterState;
            stateMachine.OnExitState += OnExitState;
        }
        else
        {
            Debug.LogWarning("No state machine assigned.", this);
        }
    }

    private void OnEnterState(State state)
    {
        Debug.Log($"Enter state with ID {state.ID}");
    }

    private void OnExitState(State state)
    {
        Debug.Log($"Exit state with ID {state.ID}");
    }
}

Last updated