122 lines
3.1 KiB
C#
122 lines
3.1 KiB
C#
using Thousandto.Core.Base;
|
|
using Thousandto.Core.Support;
|
|
using System;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
namespace Thousandto.Code.Logic
|
|
{
|
|
/// <summary>
|
|
/// 游戏状态Machine
|
|
/// </summary>
|
|
public class StateMachine
|
|
{
|
|
#region//私有变量
|
|
//状态拥有者
|
|
private IStateSystem _owner = null;
|
|
//前一状态
|
|
private IGameState _prevState = null;
|
|
//当前状态
|
|
private IGameState _curState = null;
|
|
//下一状态
|
|
private IGameState _nextState = null;
|
|
//所有状态集合
|
|
private IGameState[] _statesCache = null;
|
|
#endregion
|
|
|
|
#region//构造函数
|
|
public StateMachine(IStateSystem owner)
|
|
{
|
|
_owner = owner;
|
|
Initialize();
|
|
}
|
|
#endregion
|
|
|
|
#region//私有函数
|
|
public void Initialize()
|
|
{
|
|
}
|
|
#endregion
|
|
|
|
#region//公共函数
|
|
//获取前一状态
|
|
public IGameState GetPrevState()
|
|
{
|
|
return _prevState;
|
|
}
|
|
//获取当前状态
|
|
public IGameState GetCurState()
|
|
{
|
|
return _curState;
|
|
}
|
|
//获取下一状态
|
|
public IGameState GetNextState()
|
|
{
|
|
return _nextState;
|
|
}
|
|
public void HandlerMessage(object arg)
|
|
{
|
|
if (_curState != null)
|
|
_curState.HandlerMessage(arg);
|
|
}
|
|
//切换状态
|
|
public void ChangeState(int stateId, object arg = null)
|
|
{
|
|
try
|
|
{
|
|
IGameState newState = _owner.GetStateById(stateId);
|
|
if (newState != null && newState.Check(_prevState))
|
|
{
|
|
_prevState = _curState;
|
|
_nextState = newState;
|
|
_nextState.Arg = arg;
|
|
//退出前一状态
|
|
if (_prevState != null)
|
|
_prevState.Leave();
|
|
//进入下一状态
|
|
if (_nextState != null)
|
|
{
|
|
_curState = _nextState;
|
|
_curState.Enter();
|
|
}
|
|
}
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
UnityEngine.Debug.LogError(string.Format("游戏状态切换失败!!!!{0}", e));
|
|
}
|
|
}
|
|
|
|
//判断当前状态是否是传入stateId对应的状态
|
|
public bool IsState(int stateId)
|
|
{
|
|
if (_curState != null)
|
|
{
|
|
return _curState.GetStateId() == stateId;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
public bool Update(float dt)
|
|
{
|
|
if (_curState != null)
|
|
{
|
|
_curState.Update(dt);
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
public void Clear()
|
|
{
|
|
_prevState = null;
|
|
_curState = null;
|
|
_nextState = null;
|
|
_statesCache = null;
|
|
}
|
|
#endregion
|
|
}
|
|
}
|
|
|