1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- using UnityEngine;
- namespace Ragdoll
- {
- // 单例的状态机
- public abstract class RdSingletonStateMachine<T, K> : RdStateMachine<T> where T : RdState where K : new()
- {
- private static K _instance;
- private static readonly object Lock = new object();
- public static K Instance
- {
- get
- {
- if (_instance == null)
- // 上锁,防止重复实例化
- lock (Lock)
- {
- _instance ??= new K();
- }
- return _instance;
- }
- }
- }
- public abstract class RdStateMachine<T> where T : RdState
- {
- protected T currentState;
- protected abstract void Start();
- public virtual T GetCurState()
- {
- return currentState;
- }
- public virtual void TransitionToState(T nextState)
- {
- Debug.Log("change state ->" + nextState.ToString());
- // 退出当前状态
- if (currentState != null)
- {
- currentState.ExitState();
- }
- // 切换到下一个状态
- currentState = nextState;
- // 进入下一个状态
- if (currentState != null)
- {
- currentState.EnterState();
- }
- }
- }
- public interface RdState
- {
- public abstract void EnterState();
- public abstract void ExitState();
- }
- }
|