//添加新状态到字典 protected void AddState <T>() where T : NPCStateBase { //添加状态类的脚本到物体 NPCStateBase state = gameObject.AddComponent <T>(); state.OnInit(); //初始化 states.Add(state.GetType(), state); //添加到状态集合 }
//切换状态 public bool ChangeState <T>() where T : NPCStateBase { if (states[typeof(T)] == null) //如果不存在该状态 { return(false); } if (currentState != null) { currentState.OnExit(); //旧状态 离开回调 } currentState = states[typeof(T)]; //重新赋值当前状态 currentState.OnEnter(); //新状态 进入回调 return(true); }