MaterialFactory.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using System;
  2. using System.Collections.Generic;
  3. namespace UnityEngine.PostProcessing
  4. {
  5. using UnityObject = Object;
  6. public sealed class MaterialFactory : IDisposable
  7. {
  8. Dictionary<string, Material> m_Materials;
  9. public MaterialFactory()
  10. {
  11. m_Materials = new Dictionary<string, Material>();
  12. }
  13. public Material Get(string shaderName)
  14. {
  15. Material material;
  16. if (!m_Materials.TryGetValue(shaderName, out material))
  17. {
  18. var shader = Shader.Find(shaderName);
  19. if (shader == null)
  20. throw new ArgumentException(string.Format("Shader not found ({0})", shaderName));
  21. material = new Material(shader)
  22. {
  23. name = string.Format("PostFX - {0}", shaderName.Substring(shaderName.LastIndexOf("/") + 1)),
  24. hideFlags = HideFlags.DontSave
  25. };
  26. m_Materials.Add(shaderName, material);
  27. }
  28. return material;
  29. }
  30. public void Dispose()
  31. {
  32. var enumerator = m_Materials.GetEnumerator();
  33. while (enumerator.MoveNext())
  34. {
  35. var material = enumerator.Current.Value;
  36. GraphicsUtils.Destroy(material);
  37. }
  38. m_Materials.Clear();
  39. }
  40. }
  41. }