public enum PersonState
{
EatMeal, //--->0
Work, //--->1
Sleep, //--->2
Chat //--->3
}
public class StateTest : MonoBehaviour
{
//当前帧的状态
public PersonState mState = PersonState.EatMeal;
//上一帧的状态
private PersonState lastState;
A----------------------------------------------------------------------------------------------------------------------
void Start () {
//枚举类型和int直接可以很友好的进行转换
state = PersonState.Sleep;
Debug.Log((int)state);
int a = 3;
PersonState stateConvert = (PersonState)a;
Debug.Log(stateConvert);
}
此处打印出来2,chat
如图所示
B-------------------------------------------------------------------------------------------------------------------
void Update () {
if (state ==PersonState.EatMeal)
{
//根据当前的状态 书写当前状态下的逻辑
Debug.Log("吃饭中");
}
else if (state == PersonState.Sleep)
{
Debug.Log("睡觉中");
}
else if (state == PersonState.Work)
{
Debug.Log("滚,我在工作");
}
else
{
Debug.Log("我在撩妹,爬一边去");
}
C---------------------------------------------------------------------------------------------------------------------------
if (mState != lastState)
{
//状态机 状态机管控者
Context context = new Context();
//一个状态 sleep状态
IState state = new Sleep(context);
switch (mState)
{
case PersonState.Sleep:
state = new Sleep(context);
break;
case PersonState.EatMeal:
state = new EatMeal(context);
break;
case PersonState.Work:
state = new Work(context);
break;
case PersonState.Chat:
state = new Chat(context);
break;
default:
break;
}
context.SetState(state);
context.Handle();
lastState = mState;//更新上一状态为本帧状态
}
}
}
public interface IState//状态的接口
{
void Handle();//方法是 当前状态 应该处理的事情
}
public class Context//状态机
{
private IState mState;//当前状态
//设置当前状态
public void SetState(IState state)
{
mState = state;
}
public void Handle()
{
mState.Handle();//执行当前状态下的方法
}
}
public class Sleep : IState
{
//成员变量 状态属性
//当前状态 所属的管控领导
private Context mContext;
public Sleep(Context context)
{
mContext = context;//对当前状态属性(状态机管理者属性) 进行赋值
}
public void Handle()
{
Debug.Log("你他妈滚蛋,劳资在睡觉");
}
}
public class Work : IState
{
//成员变量 状态属性
//当前状态 所属的管控领导
private Context mContext;
public Work(Context context)
{
mContext = context;//对当前状态属性(状态机管理者属性) 进行赋值
}
public void Handle()
{
Debug.Log("加班加班,人生真苦,及时行乐");
}
}
public class EatMeal : IState
{
//成员变量 状态属性
//当前状态 所属的管控领导
private Context mContext;
public EatMeal(Context context)
{
mContext = context;//对当前状态属性(状态机管理者属性) 进行赋值
}
public void Handle()
{
Debug.Log("吃吃吃,就知道吃");
}
}
public class Chat : IState
{
//成员变量 状态属性
//当前状态 所属的管控领导
private Context mContext;
public Chat(Context context)
{
mContext = context;//对当前状态属性(状态机管理者属性) 进行赋值
}
public void Handle()
{
Debug.Log("不要打扰为父,为父在跟瑶妹聊天");
}
}
状态机