RdStateMachine.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using UnityEngine;
  2. namespace Ragdoll
  3. {
  4. // 单例的状态机
  5. public abstract class RdSingletonStateMachine<T, K> : RdStateMachine<T> where T : RdState where K : new()
  6. {
  7. private static K _instance;
  8. private static readonly object Lock = new object();
  9. public static K Instance
  10. {
  11. get
  12. {
  13. if (_instance == null)
  14. // 上锁,防止重复实例化
  15. lock (Lock)
  16. {
  17. _instance ??= new K();
  18. }
  19. return _instance;
  20. }
  21. }
  22. }
  23. public abstract class RdStateMachine<T> where T : RdState
  24. {
  25. protected T currentState;
  26. protected abstract void Start();
  27. public virtual T GetCurState()
  28. {
  29. return currentState;
  30. }
  31. public virtual void TransitionToState(T nextState)
  32. {
  33. Debug.Log("change state ->" + nextState.ToString());
  34. // 退出当前状态
  35. if (currentState != null)
  36. {
  37. currentState.ExitState();
  38. }
  39. // 切换到下一个状态
  40. currentState = nextState;
  41. // 进入下一个状态
  42. if (currentState != null)
  43. {
  44. currentState.EnterState();
  45. }
  46. }
  47. }
  48. public interface RdState
  49. {
  50. public abstract void EnterState();
  51. public abstract void ExitState();
  52. }
  53. }