SerieLabelPool.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /************************************************/
  2. /* */
  3. /* Copyright (c) 2018 - 2021 monitor1394 */
  4. /* https://github.com/monitor1394 */
  5. /* */
  6. /************************************************/
  7. using System.Collections.Generic;
  8. using UnityEngine;
  9. using UnityEngine.UI;
  10. namespace XCharts
  11. {
  12. internal static class SerieLabelPool
  13. {
  14. private static readonly Stack<GameObject> m_Stack = new Stack<GameObject>(200);
  15. private static Dictionary<int, bool> m_ReleaseDic = new Dictionary<int, bool>(1000);
  16. public static GameObject Get(string name, Transform parent, SerieLabel label, Color color,
  17. float iconWidth, float iconHeight, ChartTheme theme)
  18. {
  19. GameObject element;
  20. if (m_Stack.Count == 0 || !Application.isPlaying)
  21. {
  22. element = CreateSerieLabel(name, parent, label, color, iconWidth, iconHeight, theme);
  23. }
  24. else
  25. {
  26. element = m_Stack.Pop();
  27. if (element == null)
  28. {
  29. element = CreateSerieLabel(name, parent, label, color, iconWidth, iconHeight, theme);
  30. }
  31. m_ReleaseDic.Remove(element.GetInstanceID());
  32. element.name = name;
  33. element.transform.SetParent(parent);
  34. element.transform.localEulerAngles = new Vector3(0, 0, label.textStyle.rotate);
  35. var text = new ChartText(element);
  36. text.SetColor(color);
  37. text.SetFontAndSizeAndStyle(label.textStyle, theme.common);
  38. ChartHelper.SetActive(element, true);
  39. }
  40. return element;
  41. }
  42. private static GameObject CreateSerieLabel(string name, Transform parent, SerieLabel label, Color color,
  43. float iconWidth, float iconHeight, ChartTheme theme)
  44. {
  45. var element = ChartHelper.AddSerieLabel(name, parent, label.backgroundWidth, label.backgroundHeight,
  46. color, label.textStyle, theme);
  47. ChartHelper.AddIcon("Icon", element.transform, iconWidth, iconHeight);
  48. return element;
  49. }
  50. public static void Release(GameObject element)
  51. {
  52. if (element == null) return;
  53. ChartHelper.SetActive(element, false);
  54. if (!Application.isPlaying) return;
  55. if (!m_ReleaseDic.ContainsKey(element.GetInstanceID()))
  56. {
  57. m_Stack.Push(element);
  58. m_ReleaseDic.Add(element.GetInstanceID(), true);
  59. }
  60. }
  61. public static void ReleaseAll(Transform parent)
  62. {
  63. int count = parent.childCount;
  64. for (int i = 0; i < count; i++)
  65. {
  66. Release(parent.GetChild(i).gameObject);
  67. }
  68. }
  69. public static void ClearAll()
  70. {
  71. m_Stack.Clear();
  72. m_ReleaseDic.Clear();
  73. }
  74. }
  75. }