Are there any proper ways to instantiate states in a state-machine implementation?

Viewed 73

I want to programmatically implement a state-machine in unity follow the traditional definition of it. I create an interface of IState and an interface of IStateMachine:

public interface IState {
    GameObject Entity {set;get;}
    IStateMachine SM {set;get;}
    void OnEnterState();
    void OnStayAtState();
    void OnExitState();
}

public interface IStateMachine {
    IState CurState { get; }
    bool SwitchTo(string name);
    void Reset();
}

I plan to maintain a dictionary (k: state name string, v: IState) in machine so I can switch different state by name. But I don't know how to instantiate states and put them in dictionary properly.

I have many states including Moving, Attacking, Sleeping, and some of them have complex implementation. I think I can instantiate them together when I instantiate state-machine, But it seems not a good idea. I want the machine can do something like the lazy instantiation like:

    public void SwitchTo(string name) {
        if (_states.ContainsKey(name)) {
            // Switch current state as name
        } else {
            // Do State Instantiation here and put it in dictionary
            // then switch
        }

I don't know how to implement this. Does C# have any ways to keep a class's information or constructor, I hope I can keep a static readonly dictionary like

Dictionary<string, Class> _stateList;
_stateList[stateName]::constructor();

EDIT: I thought a method. I convert the duty of instantiating IState to specific state, then register it to the state machine, like: (in WalkingState)

void Rest() {
      if(!SM.SwitchStateByName("rest")){
           // Rest state isn't instantiated as far
           IState Rest = new RestState();
           SM.AddState(Rest); // register
           SM.SwitchToState(Rest);
     }
}

I think this is a possible solution, but Im not sure it follows thought of state-machine design.

0 Answers
Related