IconCollection.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text.RegularExpressions;
  6. using Assets.HeroEditor4D.Common.Scripts.Data;
  7. using UnityEditor;
  8. using UnityEngine;
  9. namespace Assets.HeroEditor4D.Common.Scripts.Collections
  10. {
  11. /// <summary>
  12. /// Global object that automatically grabs all required images.
  13. /// </summary>
  14. [CreateAssetMenu(fileName = "IconCollection", menuName = "HeroEditor4D/IconCollection")]
  15. public class IconCollection : ScriptableObject
  16. {
  17. public string Id;
  18. public List<UnityEngine.Object> IconFolders;
  19. public List<ItemIcon> Icons;
  20. public Sprite GetIcon(string id)
  21. {
  22. var icon = id == null ? null : Icons.SingleOrDefault(i => i.Id == id);
  23. if (icon == null && id != null) Debug.LogWarning("Icon not found: " + id);
  24. return icon?.Sprite;
  25. }
  26. #if UNITY_EDITOR
  27. public void Refresh()
  28. {
  29. Icons.Clear();
  30. foreach (var folder in IconFolders)
  31. {
  32. if (folder == null) continue;
  33. var root = AssetDatabase.GetAssetPath(folder);
  34. var files = Directory.GetFiles(root, "*.png", SearchOption.AllDirectories).ToList();
  35. foreach (var path in files.Select(i => i.Replace("\\", "/")))
  36. {
  37. var match = Regex.Match(path, @"Assets\/HeroEditor4D\/(?<Edition>\w+)\/(.+?\/)*Icons\/\w+\/(?<Type>\w+)\/(?<Collection>.+?)\/(.+\/)*(?<Name>.+?)\.png");
  38. if (!match.Success) throw new Exception($"Incorrect path: {path}");
  39. var sprite = AssetDatabase.LoadAssetAtPath<Sprite>(path);
  40. var edition = match.Groups["Edition"].Value;
  41. var collection = match.Groups["Collection"].Value;
  42. var type = match.Groups["Type"].Value;
  43. var iconName = match.Groups["Name"].Value;
  44. var icon = new ItemIcon(edition, collection, type, iconName, path, sprite);
  45. if (Icons.Any(i => i.Path == icon.Path))
  46. {
  47. Debug.LogErrorFormat($"Duplicated icon: {icon.Path}");
  48. }
  49. else
  50. {
  51. Icons.Add(icon);
  52. }
  53. }
  54. }
  55. Icons = Icons.OrderBy(i => i.Name).ToList();
  56. EditorUtility.SetDirty(this);
  57. }
  58. #endif
  59. }
  60. }