ModifiedMaterial.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. namespace Coffee.UIParticleExtensions
  4. {
  5. internal class ModifiedMaterial
  6. {
  7. private static readonly List<MatEntry> s_Entries = new List<MatEntry>();
  8. public static Material Add(Material baseMat, Texture texture, int id)
  9. {
  10. MatEntry e;
  11. for (var i = 0; i < s_Entries.Count; ++i)
  12. {
  13. e = s_Entries[i];
  14. if (e.baseMat != baseMat || e.texture != texture || e.id != id) continue;
  15. ++e.count;
  16. return e.customMat;
  17. }
  18. e = new MatEntry();
  19. e.count = 1;
  20. e.baseMat = baseMat;
  21. e.texture = texture;
  22. e.id = id;
  23. e.customMat = new Material(baseMat);
  24. e.customMat.hideFlags = HideFlags.HideAndDontSave;
  25. if (texture)
  26. e.customMat.mainTexture = texture;
  27. s_Entries.Add(e);
  28. // Debug.LogFormat(">>>> ModifiedMaterial.Add -> count = {0} {1} {2} {3}", s_Entries.Count, baseMat, texture, id);
  29. return e.customMat;
  30. }
  31. public static void Remove(Material customMat)
  32. {
  33. if (!customMat) return;
  34. for (var i = 0; i < s_Entries.Count; ++i)
  35. {
  36. var e = s_Entries[i];
  37. if (e.customMat != customMat) continue;
  38. if (--e.count == 0)
  39. {
  40. // Debug.LogFormat(">>>> ModifiedMaterial.Add -> count = {0} {1} {2} {3}", s_Entries.Count - 1, e.customMat, e.texture, e.id);
  41. DestroyImmediate(e.customMat);
  42. e.baseMat = null;
  43. e.texture = null;
  44. s_Entries.RemoveAt(i);
  45. }
  46. break;
  47. }
  48. }
  49. private static void DestroyImmediate(Object obj)
  50. {
  51. if (!obj) return;
  52. if (Application.isEditor)
  53. Object.DestroyImmediate(obj);
  54. else
  55. Object.Destroy(obj);
  56. }
  57. private class MatEntry
  58. {
  59. public Material baseMat;
  60. public Material customMat;
  61. public int count;
  62. public Texture texture;
  63. public int id;
  64. }
  65. }
  66. }