Unity3d-Finite-State-Machine icon indicating copy to clipboard operation
Unity3d-Finite-State-Machine copied to clipboard

Expandable state machine

Open Xriuk opened this issue 2 years ago • 0 comments

Upgrading the FSM to allow inheritance and expansion of the states, this partially breaks backwards compatibility (It can be still used as it is with the static API).

It retains compatibility with new Drivers as well.

Here's how it works:

using MonsterLove.StateMachine;

public class MyGameplayScript : MonoBehaviour
{
    public enum States
    {
        Init, 
        Play, 
        Win, 
        Lose,
        Total
    }
    
    StateMachine fsm;
    
    protected void Awake(){
        fsm = new StateMachine(this);

        // Here we add current states
        fsm.AddStates<States>();

        fsm.ChangeState(States.Init);
    }

    protected virtual void Init_Enter()
    {
        Debug.Log("Ready");
    }

    protected virtual void Play_Enter()
    {      
        Debug.Log("Spawning Player");    
    }

    protected virtual void Play_FixedUpdate()
    {
        Debug.Log("Doing Physics stuff");
    }

    protected virtual void Play_Update()
    {
        if(player.health <= 0)
        {
            fsm.ChangeState(States.Lose);
        }
    }

    protected virtual void Play_Exit()
    {
        Debug.Log("Despawning Player");    
    }

    protected virtual void Win_Enter()
    {
        Debug.Log("Game Over - you won!");
    }

    protected virtual void Lose_Enter()
    {
        Debug.Log("Game Over - you lost!");
    }

}

public class MyChild : MyGameplayScript {
    public enum States2
    {
        Jump = MyGameplayScript.States.Total, // This is used to continue the enumeration, as each number is unique
        Die, 
        Total
    }

    protected void Awake(){
        // Initialize parent states
        base.Awake();
        
        // Here we add current states
        fsm.AddStates<States2>();

        // Change state if needed
        fsm.ChangeState(States2.Jump);
    }

    // Overriding existing state
    override protected void Lose_Enter()
    {
        Debug.Log("You lost badly");
    }

    // Adding new state function
    protected virtual void Jump_Enter()
    {
        Debug.Log("Jumping, yay!");
    }
}

Xriuk avatar Sep 12 '21 14:09 Xriuk