ScriptableObjectSingleton.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using JetBrains.Annotations;
  5. using UnityEditorInternal;
  6. using UnityEngine;
  7. using UnityEngine.Assertions;
  8. using Object = UnityEngine.Object;
  9. namespace Unity.Cloud.Collaborate.Common
  10. {
  11. internal class ScriptableObjectSingleton<T> : ScriptableObject where T : ScriptableObject
  12. {
  13. static T s_Instance;
  14. public static T Instance
  15. {
  16. get
  17. {
  18. if (s_Instance == null)
  19. CreateAndLoad();
  20. return s_Instance;
  21. }
  22. }
  23. protected ScriptableObjectSingleton()
  24. {
  25. if (s_Instance != null)
  26. {
  27. Debug.LogError("Singleton already exists!");
  28. }
  29. else
  30. {
  31. s_Instance = this as T;
  32. Assert.IsFalse(s_Instance == null);
  33. }
  34. }
  35. static void CreateAndLoad()
  36. {
  37. Assert.IsTrue(s_Instance == null);
  38. var filePath = GetFilePath();
  39. if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
  40. {
  41. InternalEditorUtility.LoadSerializedFileAndForget(filePath);
  42. }
  43. if (s_Instance == null)
  44. {
  45. var inst = CreateInstance<T>() as ScriptableObjectSingleton<T>;
  46. Assert.IsFalse(inst == null);
  47. inst.hideFlags = HideFlags.HideAndDontSave;
  48. inst.Save();
  49. }
  50. Assert.IsFalse(s_Instance == null);
  51. }
  52. protected void Save()
  53. {
  54. if (s_Instance == null)
  55. {
  56. Debug.LogError("Cannot save singleton, no instance!");
  57. return;
  58. }
  59. var locationFilePath = GetFilePath();
  60. var directoryName = Path.GetDirectoryName(locationFilePath);
  61. if (directoryName == null) return;
  62. Directory.CreateDirectory(directoryName);
  63. InternalEditorUtility.SaveToSerializedFileAndForget(new Object[]{ s_Instance }, locationFilePath, true);
  64. }
  65. [CanBeNull]
  66. static string GetFilePath()
  67. {
  68. var attr = typeof(T).GetCustomAttributes(true)
  69. .OfType<LocationAttribute>()
  70. .FirstOrDefault();
  71. return attr?.FilePath;
  72. }
  73. }
  74. }