StateControl.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System;
  2. using Utility;
  3. namespace Core.State
  4. {
  5. public class StateControl: IDisposable
  6. {
  7. public Map<string, IState> States
  8. {
  9. get { return _states; }
  10. }
  11. private Map<string, IState> _states = new Map<string, IState>();
  12. public IState CurrIState
  13. {
  14. get { return _currIState; }
  15. }
  16. private IState _currIState;
  17. public void AddState(string name, IState state)
  18. {
  19. _states[name] = state;
  20. }
  21. public void Update(float t)
  22. {
  23. if (_currIState != null)
  24. {
  25. _currIState.Update(t);
  26. }
  27. }
  28. public void ChangeState(string name)
  29. {
  30. if (!_states.TryGetValue(name,out IState state))
  31. {
  32. return;
  33. }
  34. if (_currIState != null)
  35. {
  36. _currIState.Exit();
  37. }
  38. _currIState = state;
  39. _currIState.Enter();
  40. }
  41. public void Dispose()
  42. {
  43. for (int i = 0; i < _states.Count; i++)
  44. {
  45. IState istate = _states.GetValueByIndex(i);
  46. if (istate != null)
  47. {
  48. istate.Dispose();
  49. }
  50. }
  51. }
  52. }
  53. }