UxmlLoader.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #if UNITY_2019_4_OR_NEWER
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEditor;
  5. using UnityEngine;
  6. using UnityEditor.UIElements;
  7. using UnityEngine.UIElements;
  8. namespace YooAsset.Editor
  9. {
  10. public class UxmlLoader
  11. {
  12. private readonly static Dictionary<System.Type, string> _uxmlDic = new Dictionary<System.Type, string>();
  13. /// <summary>
  14. /// 加载窗口的布局文件
  15. /// </summary>
  16. public static UnityEngine.UIElements.VisualTreeAsset LoadWindowUXML<TWindow>() where TWindow : class
  17. {
  18. var windowType = typeof(TWindow);
  19. // 缓存里查询并加载
  20. if (_uxmlDic.TryGetValue(windowType, out string uxmlGUID))
  21. {
  22. string assetPath = AssetDatabase.GUIDToAssetPath(uxmlGUID);
  23. if (string.IsNullOrEmpty(assetPath))
  24. {
  25. _uxmlDic.Clear();
  26. throw new System.Exception($"Invalid UXML GUID : {uxmlGUID} ! Please close the window and open it again !");
  27. }
  28. var treeAsset = AssetDatabase.LoadAssetAtPath<UnityEngine.UIElements.VisualTreeAsset>(assetPath);
  29. return treeAsset;
  30. }
  31. // 全局搜索并加载
  32. string[] guids = AssetDatabase.FindAssets(windowType.Name);
  33. if (guids.Length == 0)
  34. throw new System.Exception($"Not found any assets : {windowType.Name}");
  35. foreach (string assetGUID in guids)
  36. {
  37. string assetPath = AssetDatabase.GUIDToAssetPath(assetGUID);
  38. var assetType = AssetDatabase.GetMainAssetTypeAtPath(assetPath);
  39. if (assetType == typeof(UnityEngine.UIElements.VisualTreeAsset))
  40. {
  41. _uxmlDic.Add(windowType, assetGUID);
  42. var treeAsset = AssetDatabase.LoadAssetAtPath<UnityEngine.UIElements.VisualTreeAsset>(assetPath);
  43. return treeAsset;
  44. }
  45. }
  46. throw new System.Exception($"Not found UXML file : {windowType.Name}");
  47. }
  48. }
  49. }
  50. #endif