MaterialCache.cs 2.3 KB

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