You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

117 lines
2.3 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using SUISS.Storage;
  5. using UnityEngine;
  6. namespace SUISSEngine
  7. {
  8. public class IslandState : MonoBehaviour
  9. {
  10. //[DebuggerBrowsable(DebuggerBrowsableState.Never)]
  11. public event IslandState.ValueChangedHandler ValueChanged;
  12. protected virtual void Awake()
  13. {
  14. if (this.values == null)
  15. {
  16. this.LoadState();
  17. }
  18. }
  19. protected virtual void Start()
  20. {
  21. }
  22. protected virtual void OnDestroy()
  23. {
  24. this.ValueChanged = null;
  25. }
  26. public static IslandState ParentOf(Component comp)
  27. {
  28. return comp.GetComponentInParent<IslandState>();
  29. }
  30. public virtual T GetValue<T>(string key, T defaultValue)
  31. {
  32. if (this.values == null)
  33. {
  34. this.LoadState();
  35. }
  36. object obj;
  37. if (!this.values.TryGetValue(key, out obj))
  38. {
  39. return defaultValue;
  40. }
  41. if (obj is T)
  42. {
  43. return (T)((object)obj);
  44. }
  45. return defaultValue;
  46. }
  47. public virtual void SetValue(string key, object value)
  48. {
  49. if (this.isNewGameState)
  50. {
  51. this.values[key] = value;
  52. }
  53. else
  54. {
  55. if (this.values == null)
  56. {
  57. this.LoadState();
  58. }
  59. object obj;
  60. if (!this.values.TryGetValue(key, out obj))
  61. {
  62. obj = null;
  63. }
  64. if (!object.Equals(obj, value))
  65. {
  66. this.values[key] = value;
  67. this.OnValueChanged(key, obj, value);
  68. }
  69. }
  70. }
  71. protected virtual void LoadState()
  72. {
  73. Storage storage = Storage.Get(StorageLifecycle.Game);
  74. if (storage.Root.ContainsKey(this.StorageKey))
  75. {
  76. this.values = (Dictionary<string, object>)storage.Root[this.StorageKey];
  77. }
  78. else
  79. {
  80. this.values = new Dictionary<string, object>();
  81. storage.Root[this.StorageKey] = this.values;
  82. this.isNewGameState = true;
  83. this.OnNewGameState();
  84. this.isNewGameState = false;
  85. }
  86. }
  87. protected virtual void OnValueChanged(string key, object oldValue, object newValue)
  88. {
  89. if (this.ValueChanged != null)
  90. {
  91. this.ValueChanged(key, oldValue, newValue);
  92. }
  93. }
  94. protected virtual void OnNewGameState()
  95. {
  96. }
  97. public string StorageKey;
  98. protected Dictionary<string, object> values;
  99. protected bool isNewGameState;
  100. public delegate void ValueChangedHandler(string key, object oldValue, object newValue);
  101. }
  102. }