123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- 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;
- }
- // ReSharper disable Unity.PerformanceAnalysis
- public virtual void TransitionToState(T nextState)
- {
- Debug.Log("change state -> " + nextState);
- // 退出当前状态
- if (currentState != null)
- {
- currentState.ExitState();
- }
- // 切换到下一个状态
- currentState = nextState;
- // 进入下一个状态
- if (currentState != null)
- {
- currentState.EnterState();
- }
- }
- }
- public interface RdState
- {
- public abstract void EnterState();
- public abstract void ExitState();
- }
- }
|