Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expandable state machine #40

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

Xriuk
Copy link

@Xriuk Xriuk commented Sep 12, 2021

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!");
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant