FSM 有限状态机框架
State
using UnityEngine;
using System.Collections.Generic;
using System;
namespace FSM_Frame {
//状态
public class State {
#region Constructor 构造
public State(string stateName){
this.stateName = stateName;
transitionDic = new Dictionary<string,Func<bool>>();
BindBaseStateEvents();
}
#endregion
#region State Filed 状态字段
//状态名称
protected string stateName;
//状态是否正在运行
protected bool isRun;
#endregion
#region State Properties 状态属性
public string StateName {
get{return stateName;}
set{stateName = value;}
}
public string IsRun {
get{return isRun;}
set{isRun = value;}
}
#endregion
#region State Transition 状态过度
//过度字典
// 名字 参数
private Dictionary<string,Func<bool>> transitionDic;
//注册新的状态过度 过度状态名称 过度条件
public void RegisterStateTransition(string transitionStateName,Func<bool> transitionCondition){
//如果过度条件为空
if(transitionCondition == null){
throw new Exception("注册的状态过度条件为空");
}
//添加和更新
transitionDic[transitionStateName] = transitionCondition;
}
//取消过渡
public void UnRegisterStateTransition(string transitionStateName){
if(transitionDic.ContainsKey(transitionStateName)){
throw new Exception("状态列表中无此状态,不能取消注册");
}
//移除
transitionDic.Remove(transitionStateName);
}
#endregion
#region State Events 状态事件
public event Action<object> OnStateEnter;
public event Action<object> OnStateUpdate;
public event Action<object> OnStateExit;
#endregion
#region Bind Base State Events 基础状态事件
private void BindBaseStateEvents(){
OnStateEnter += (obj) => isRun = true;
OnStateExit += (obj) => isRun = false;
}
#endregion
#region EnterState & ExitState 进入和离开
//进入当前状态
public virtual void EnterState(object enterParameter,object updateParameter){
if(OnStateEnter != null){
//执行状态进入事件
OnStateEnter(enterParameter);
}
if(OnStateUpdate != null){
//将当前的更新时间添加持续执行
MonoHelper.instance.AddUpdateEvent(stateName,OnStateUpdate,updateParameter);
}