public FSMStateMachine(string fmsName, List <AttributeTypeData> classDataList) { _stateDic = new Dictionary <Type, BaseFSMState>(); Name = fmsName; //根据Type 实例化状态 for (int i = 0; i < classDataList.Count; i++) { //获取与当前名称一致的stateBase if (((FSMTypeAttribute)classDataList[i].attribute).FSMName == fmsName) { BaseFSMState stateBase = Activator.CreateInstance(classDataList[i].type) as BaseFSMState; stateBase.StateMachine = this; stateBase.OnInit(); if (((FSMTypeAttribute)classDataList[i].attribute).isFirst) { _firstState = stateBase; } _stateDic.Add(classDataList[i].type, stateBase); } } }
/// <summary> /// 切换状态 /// </summary> /// <param name="type">状态类型</param> public void SwitchState(Type type) { if (_stateDic.ContainsKey(type)) { if (_currState == _stateDic[type]) { return; } BaseFSMState lastState = _currState; BaseFSMState nextState = _stateDic[type]; if (lastState != null) { lastState.OnLeave(nextState); } nextState.OnEnter(lastState); _currState = nextState; } else { } }
/// <summary> /// 离开状态 /// </summary> /// <param name="nextState">下一个进入的状态</param> public abstract void OnLeave(BaseFSMState nextState);
/// <summary> /// 进入状态 /// </summary> /// <param name="lastState">上一个离开的状态</param> public abstract void OnEnter(BaseFSMState lastState);
/// <summary> /// 启动默认状态 /// </summary> public void StartFirst() { _currState = _firstState; _currState.OnEnter(null); }