MaterialCache.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System;
  4. using UnityEngine;
  5. using System.Text;
  6. using UnityEngine.UI;
  7. namespace Coffee.UIEffects
  8. {
  9. public class MaterialCache
  10. {
  11. static Dictionary<Hash128, MaterialEntry> materialMap = new Dictionary<Hash128, MaterialEntry>();
  12. private class MaterialEntry
  13. {
  14. public Material material;
  15. public int referenceCount;
  16. public void Release()
  17. {
  18. if (material)
  19. {
  20. UnityEngine.Object.DestroyImmediate(material, false);
  21. }
  22. material = null;
  23. }
  24. }
  25. #if UNITY_EDITOR
  26. [UnityEditor.InitializeOnLoadMethod]
  27. private static void ClearCache()
  28. {
  29. foreach (var entry in materialMap.Values)
  30. {
  31. entry.Release();
  32. }
  33. materialMap.Clear();
  34. }
  35. #endif
  36. public static Material Register(Material baseMaterial, Hash128 hash,
  37. System.Action<Material, Graphic> onModifyMaterial, Graphic graphic)
  38. {
  39. if (!hash.isValid) return null;
  40. MaterialEntry entry;
  41. if (!materialMap.TryGetValue(hash, out entry))
  42. {
  43. entry = new MaterialEntry()
  44. {
  45. material = new Material(baseMaterial)
  46. {
  47. hideFlags = HideFlags.HideAndDontSave,
  48. },
  49. };
  50. onModifyMaterial(entry.material, graphic);
  51. materialMap.Add(hash, entry);
  52. }
  53. entry.referenceCount++;
  54. return entry.material;
  55. }
  56. public static void Unregister(Hash128 hash)
  57. {
  58. MaterialEntry entry;
  59. if (!hash.isValid || !materialMap.TryGetValue(hash, out entry)) return;
  60. if (--entry.referenceCount > 0) return;
  61. entry.Release();
  62. materialMap.Remove(hash);
  63. }
  64. }
  65. }