SettingLoader.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEditor;
  5. namespace YooAsset.Editor
  6. {
  7. public class SettingLoader
  8. {
  9. /// <summary>
  10. /// 加载相关的配置文件
  11. /// </summary>
  12. public static TSetting LoadSettingData<TSetting>() where TSetting : ScriptableObject
  13. {
  14. var settingType = typeof(TSetting);
  15. var guids = AssetDatabase.FindAssets($"t:{settingType.Name}");
  16. if (guids.Length == 0)
  17. {
  18. Debug.LogWarning($"Create new {settingType.Name}.asset");
  19. var setting = ScriptableObject.CreateInstance<TSetting>();
  20. string filePath = $"Assets/{settingType.Name}.asset";
  21. AssetDatabase.CreateAsset(setting, filePath);
  22. AssetDatabase.SaveAssets();
  23. AssetDatabase.Refresh();
  24. return setting;
  25. }
  26. else
  27. {
  28. if (guids.Length != 1)
  29. {
  30. foreach (var guid in guids)
  31. {
  32. string path = AssetDatabase.GUIDToAssetPath(guid);
  33. Debug.LogWarning($"Found multiple file : {path}");
  34. }
  35. throw new System.Exception($"Found multiple {settingType.Name} files !");
  36. }
  37. string filePath = AssetDatabase.GUIDToAssetPath(guids[0]);
  38. var setting = AssetDatabase.LoadAssetAtPath<TSetting>(filePath);
  39. return setting;
  40. }
  41. }
  42. }
  43. }