FontUpdateTracker.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace UnityEngine.UI
  5. {
  6. /// <summary>
  7. /// Utility class that is used to help with Text update.
  8. /// </summary>
  9. /// <remarks>
  10. /// When Unity rebuilds a font atlas a callback is sent to the font. Using this class you can register your text as needing to be rebuilt if the font atlas is updated.
  11. /// </remarks>
  12. public static class FontUpdateTracker
  13. {
  14. static Dictionary<Font, HashSet<Text>> m_Tracked = new Dictionary<Font, HashSet<Text>>();
  15. /// <summary>
  16. /// Register a Text element for receiving texture atlas rebuild calls.
  17. /// </summary>
  18. /// <param name="t">The Text object to track</param>
  19. public static void TrackText(Text t)
  20. {
  21. if (t.font == null)
  22. return;
  23. HashSet<Text> exists;
  24. m_Tracked.TryGetValue(t.font, out exists);
  25. if (exists == null)
  26. {
  27. // The textureRebuilt event is global for all fonts, so we add our delegate the first time we register *any* Text
  28. if (m_Tracked.Count == 0)
  29. Font.textureRebuilt += RebuildForFont;
  30. exists = new HashSet<Text>();
  31. m_Tracked.Add(t.font, exists);
  32. }
  33. exists.Add(t);
  34. }
  35. private static void RebuildForFont(Font f)
  36. {
  37. HashSet<Text> texts;
  38. m_Tracked.TryGetValue(f, out texts);
  39. if (texts == null)
  40. return;
  41. foreach (var text in texts)
  42. text.FontTextureChanged();
  43. }
  44. /// <summary>
  45. /// Deregister a Text element from receiving texture atlas rebuild calls.
  46. /// </summary>
  47. /// <param name="t">The Text object to no longer track</param>
  48. public static void UntrackText(Text t)
  49. {
  50. if (t.font == null)
  51. return;
  52. HashSet<Text> texts;
  53. m_Tracked.TryGetValue(t.font, out texts);
  54. if (texts == null)
  55. return;
  56. texts.Remove(t);
  57. if (texts.Count == 0)
  58. {
  59. m_Tracked.Remove(t.font);
  60. // There is a global textureRebuilt event for all fonts, so once the last Text reference goes away, remove our delegate
  61. if (m_Tracked.Count == 0)
  62. Font.textureRebuilt -= RebuildForFont;
  63. }
  64. }
  65. }
  66. }