FSM
using UnityEngine;
public class FSM<T>
{
private T owner;
public IFSMState<T> CurrentState { get; private set; }
public IFSMState<T> PreviousState { get; private set; }
public FSM(T owner)
{
this.owner = owner;
}
public void Update()
{
if (CurrentState != null)
{
CurrentState.Execute(owner);
}
}
public void ChangeState(IFSMState<T> newState)
{
PreviousState = CurrentState;
if (CurrentState != null)
{
CurrentState.Exit(owner);
}
CurrentState = newState;
if (CurrentState != null)
{
CurrentState.Enter(owner);
}
}
public void RevertState()
{
ChangeState(PreviousState);
}
public bool IsCurrentState(IFSMState<T> state)
{
if (CurrentState != null)
{
return CurrentState.GetType() == state.GetType();
}
return false;
}
public void Clear()
{
}
}
IFSMState
using UnityEngine;
using System.Collections;
public interface IFSMState<T>
{
void Enter(T owner);
void Execute(T owner);
void Exit(T owner);
}
RoleCtrl
using Pathfinding;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
public class RoleCtrl : MonoBehaviour
{
//状态
[HideInInspector] [NonSerialized] public FSM<RoleCtrl> fsm;
private void Awake()
{
this.fsm = new FSM<RoleCtrl>(this);
this.fsm.ChangeState(new HeroWalkState());
}
private void Update()
{
if (this.fsm != null)
{
this.fsm.Update();
}
}
}
HeroWalkState
using UnityEngine;
using System.Collections;
using System.IO;
//走路状态
public class HeroWalkState : IFSMState<RoleCtrl>
{
public void Enter(RoleCtrl owner)
{
//初始化
}
public void Execute(RoleCtrl owner)
{
//update更新
}
public void Exit(RoleCtrl owner)
{
//销毁
}
}