封装传递的数据类型
public class StateDeve
{
public Type type;//类型
public object data;//任意数据
//回调类型自己就是自己
public static StateDeve Creat(Type type, object data) {
StateDeve state = new StateDeve();
state.type = type;
state.data = data;
return state;
}
}
状态的基类
public abstract class StateBase
{
public abstract int ID { get; }
public abstract void Enter(StateDeve stateDeve);//开始
public abstract void Stye (StateDeve stateDeve);//执行中
public abstract void Exite(StateDeve stateDeve);//结束
}
状态机
public class FsmCure
{
public StateBase curstateBase;//当前状态
public StateBase pvrstateBase;//上一个状态
public StateDeve date;//类型
public void Change(StateBase state,StateDeve curdate,StateDeve pvrdata) {
if (curstateBase != null && state.ID == curstateBase.ID) return;
//结束状态
if (pvrstateBase != null) pvrstateBase.Exite(pvrdata);
//当前状态为传进来的类型
curstateBase = state;
//类型为当前类型
date = curdate;
//开始
curstateBase.Enter(date);
}
/// <summary>
/// 为执行Change方法
/// </summary>
/// <param name="state"></param>
/// <param name="curdate"></param>
/// <param name="pvrdata"></param>
public void Start(StateBase state, StateDeve curdate, StateDeve pvrdata)
{
Change(state,curdate,pvrdata);
}
/// <summary>
/// 执行中的状态
/// </summary>
public void Update()
{
if (curstateBase == null) return;
curstateBase.Equals(date);
}
}
例子 某个脚本调用等待状态
public class FsmModle : MonoBehaviour
{
FsmCure fsm;//状态机控制
FsmGame fsmgo;//封装的 this 类
StateDeve fsdata;//封装的类型
public void Init()
{
fsm = new FsmCure();
fsmgo = new FsmGame();
//获取本身的动画
fsmgo.anim = this.GetComponent<Animator>();
//获取本身
fsmgo.obj = this.gameObject;
//获取状态机
fsmgo.fsm = fsm;
//把类型封装好准备传
fsdata = StateDeve.Creat(fsmgo.GetType(),fsmgo);
}
// Start is called before the first frame update
void Start()
{
//调用初始化
Init();
fsm.Start(new Idle(),fsdata,null);
}
// Update is called once per frame
void Update()
{
}
}
//定义一个本身类
public class FsmGame {
public Type type = typeof(FsmGame);
public Animator anim;
public GameObject obj;
public FsmCure fsm;
}
例子 等待状态
public class Idle : StateBase
{
public override int ID { get {
return 0;
} }
public override void Enter(StateDeve stateDeve)
{
FsmGame fsmGame=(stateDeve.data) as FsmGame;
//fsmGame.anim.(…);动画随意
Debug.Log(“1”);
}
public override void Exite(StateDeve stateDeve)
{
FsmGame fsmGame = (stateDeve.data) as FsmGame;
//fsmGame.anim.(.......);动画随意
Debug.Log("3");
}
public override void Stye(StateDeve stateDeve)
{
FsmGame fsmGame = (stateDeve.data) as FsmGame;
//fsmGame.anim.(.......);动画随意
Debug.Log("2");
}
}