Inspiaaa / UnityHFSM

A simple yet powerful class-based hierarchical finite state machine for Unity
MIT License
1.14k stars 125 forks source link

[Question] Support for parallel states #38

Closed TdXYZ closed 6 months ago

TdXYZ commented 10 months ago

One of the core features of a statechart as described here https://statecharts.dev/what-is-a-statechart.html, is the ability for a state to have two or more state machines running in parallel. Does the package support this? I couldn't quite see anything like that in the documentation.

Inspiaaa commented 6 months ago

Hi @TdXYZ, the current version of UnityHFSM does not directly provide this feature out of the box. You can, however, do this fairly easily yourself:

Instead of creating just one state machine, as you normally would, you create two state machines. Then in the Update function, you call the OnLogic method of both state machines. This will run both state machines independently, in parallel.

class Player : MonoBehaviour
{
    StateMachine movementFsm;
    StateMachine animationFsm;

    void Start()
    {
        movementFsm = new StateMachine();
        movementFsm.AddState("Idle");
        movementFsm.AddState("Jump");
        movementFsm.AddState("Run");
        // ...

        animationFsm = new StateMachine();
        // ...

        movementFsm.Init();
        animationFsm.Init();
    }

    void Update() 
    {
        movementFsm.OnLogic();
        animationFsm.OnLogic();
    }
}

This same pattern can also be repeated to run as many state machines in parallel as you desire.

The implementation for running multiple nested state machines in parallel within a main state machine follows the same idea. The main difference is that their OnEnter, OnLogic, and OnExit functions would be called within an additional state that you have to add to the main state machine.

As this feature seems quite useful, I've created a new state type that does just that for you. It's called ParallelStates and will be added in the next release of UnityHFSM (2.1). If you want to already use it in the meantime, you can access it in the release branch.

TdXYZ commented 6 months ago

Thank you very much for adding this. UnityHFSM is one of the best implementations of statecharts out there. Working with the package has given me more ideas on how it can be even better such as history states and tasks, but I'll make separate issues for those.