SavedParameter.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using UnityEngine.Assertions;
  3. namespace UnityEditor.Rendering.Universal
  4. {
  5. class SavedParameter<T>
  6. where T : IEquatable<T>
  7. {
  8. internal delegate void SetParameter(string key, T value);
  9. internal delegate T GetParameter(string key, T defaultValue);
  10. readonly string m_Key;
  11. bool m_Loaded;
  12. T m_Value;
  13. readonly SetParameter m_Setter;
  14. readonly GetParameter m_Getter;
  15. public SavedParameter(string key, T value, GetParameter getter, SetParameter setter)
  16. {
  17. Assert.IsNotNull(setter);
  18. Assert.IsNotNull(getter);
  19. m_Key = key;
  20. m_Loaded = false;
  21. m_Value = value;
  22. m_Setter = setter;
  23. m_Getter = getter;
  24. }
  25. void Load()
  26. {
  27. if (m_Loaded)
  28. return;
  29. m_Loaded = true;
  30. m_Value = m_Getter(m_Key, m_Value);
  31. }
  32. public T value
  33. {
  34. get
  35. {
  36. Load();
  37. return m_Value;
  38. }
  39. set
  40. {
  41. Load();
  42. if (m_Value.Equals(value))
  43. return;
  44. m_Value = value;
  45. m_Setter(m_Key, value);
  46. }
  47. }
  48. }
  49. // Pre-specialized class for easier use and compatibility with existing code
  50. sealed class SavedBool : SavedParameter<bool>
  51. {
  52. public SavedBool(string key, bool value)
  53. : base(key, value, EditorPrefs.GetBool, EditorPrefs.SetBool) { }
  54. }
  55. sealed class SavedInt : SavedParameter<int>
  56. {
  57. public SavedInt(string key, int value)
  58. : base(key, value, EditorPrefs.GetInt, EditorPrefs.SetInt) { }
  59. }
  60. sealed class SavedFloat : SavedParameter<float>
  61. {
  62. public SavedFloat(string key, float value)
  63. : base(key, value, EditorPrefs.GetFloat, EditorPrefs.SetFloat) { }
  64. }
  65. sealed class SavedString : SavedParameter<string>
  66. {
  67. public SavedString(string key, string value)
  68. : base(key, value, EditorPrefs.GetString, EditorPrefs.SetString) { }
  69. }
  70. }