Advertisement

Finite State Machine using Command Pattern?

Started by December 15, 2015 11:34 PM
1 comment, last by Artificial_Idiot 8 years, 11 months ago

class EnemyController : MonoBehaviour
{
    IState PatrolState;
    IState AttackState;

    StateMachine FSM;

    void Awake()
    {
        //The state has an Action delegate as an argument called Enter, Execute, Exit in order
        PatrolState = new State(StartWalkingAnim, Patrol, StopWalkingAnim);
        //an overloaded one with only execute as an argument
        AttackState = new State(Attack);

        FSM = new StateMachine();
        FSM.SetCurrentState(AttackState);
    }

    void Update()
    {
        FSM.Update();
    }

    private void StopWalkingAnim()
    {
        //stop walking animation
    }

    private void StartWalkingAnim()
    {
        //stop walking animation
    }

    private void Patrol()
    {
        //if (player.Onsight) 
        //   FSM.ChangeState(Attack)

        //movement.Patrol();
    }

    private void Attack()
    {
        //if (!player.Onsight) 
        //   FSM.ChangeState(Idle)

        //AttackController.Attack();
    }

}


The benefit I could see here is all the functions has a direct access to member variables so no passing of reference is necessary. and also no need for seperate class for each state. this is inspired by the command pattern in WPF and Xaml databinding

what do you guys think? do you think this will scale? if not whats the way to make this better? or something is fundamentally wrong here?

I have been using state machines with Unity and thing that is definately a good way to go.

I would, however, make a state a separate class you instantiate and pass the EnemyController into.



PatrolState = new PatrolState(this);

Having all of your states bundled as methods will make your code hard to reuse. If you have your EnemyController implement an interface, something like IMovingObject. Then you can make PartrolState accept an IMovingObject in its constructor so you can resuse PatrolState on anything that is an IMovingObject.

I would also not have a state for specific animation. I would let mechanim take care of the animating. IMHO, you state machine should function identically with or without animations. That way your animation and art can be updated without effecting gameplay.
My current game project Platform RPG
Advertisement
how are you decoupling your animation with mecanim?

I usually do this
OnStateEnter()
{
Anim.Setbool(walking,true);
}

This topic is closed to new replies.

Advertisement