Statistics.cs 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using Sirenix.OdinInspector;
  5. namespace KairoEngine.Utilities.Statistics
  6. {
  7. [HideMonoScript]
  8. public class Statistics : SerializedMonoBehaviour
  9. {
  10. #region Singleton
  11. private static Statistics statistics;
  12. public static Statistics instance
  13. {
  14. get {
  15. if(!statistics)
  16. {
  17. statistics = FindObjectOfType (typeof(Statistics)) as Statistics;
  18. if(!statistics)
  19. {
  20. Debug.LogError("There need to one active Statistics script on the scene.");
  21. return null;
  22. }
  23. }
  24. return statistics;
  25. }
  26. }
  27. #endregion
  28. [ListDrawerSettings(ShowPaging = false)]
  29. public List<StatisticData> data = new List<StatisticData>();
  30. void Awake()
  31. {
  32. if(instance != null && instance != this)
  33. {
  34. Destroy(this.gameObject);
  35. return;
  36. }
  37. LoadStatistics();
  38. }
  39. void OnDestroy()
  40. {
  41. SaveStatistics();
  42. }
  43. public static StatisticData GetData(string title)
  44. {
  45. if(instance == null) return null;
  46. for (int i = 0; i < instance.data.Count; i++)
  47. {
  48. if(instance.data[i].title == title) return instance.data[i];
  49. }
  50. return null;
  51. }
  52. private void LoadStatistics()
  53. {
  54. if(instance == null) return;
  55. for (int i = 0; i < instance.data.Count; i++)
  56. {
  57. StatisticData stat = instance.data[i];
  58. if(stat.persistent == false) continue;
  59. switch (stat.category)
  60. {
  61. case StatisticType.time:
  62. float time = PlayerPrefs.GetFloat(stat.title, 0f);
  63. stat.SetTime(time);
  64. break;
  65. case StatisticType.integer:
  66. int integer = PlayerPrefs.GetInt(stat.title, 0);
  67. stat.SetInteger(integer);
  68. break;
  69. case StatisticType.text:
  70. string text = PlayerPrefs.GetString(stat.title, "");
  71. stat.SetText(text);
  72. break;
  73. default:
  74. break;
  75. }
  76. }
  77. }
  78. private void SaveStatistics()
  79. {
  80. if(instance == null) return;
  81. for (int i = 0; i < instance.data.Count; i++)
  82. {
  83. StatisticData stat = instance.data[i];
  84. if(stat.persistent == false) continue;
  85. switch (stat.category)
  86. {
  87. case StatisticType.time:
  88. PlayerPrefs.SetFloat(stat.title, stat.GetTime());
  89. break;
  90. case StatisticType.integer:
  91. PlayerPrefs.SetInt(stat.title, stat.GetInteger());
  92. break;
  93. case StatisticType.text:
  94. PlayerPrefs.SetString(stat.title, stat.GetText());
  95. break;
  96. default:
  97. break;
  98. }
  99. }
  100. }
  101. }
  102. }