RdStateMachine.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. // ReSharper disable Unity.PerformanceAnalysis
  32. public virtual void TransitionToState(T nextState)
  33. {
  34. Debug.Log("change state -> " + nextState);
  35. // 退出当前状态
  36. if (currentState != null)
  37. {
  38. currentState.ExitState();
  39. }
  40. // 切换到下一个状态
  41. currentState = nextState;
  42. // 进入下一个状态
  43. if (currentState != null)
  44. {
  45. currentState.EnterState();
  46. }
  47. }
  48. }
  49. public interface RdState
  50. {
  51. public abstract void EnterState();
  52. public abstract void ExitState();
  53. }
  54. }