LoopHorizontalScrollRect.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. using UnityEngine;
  2. using System.Collections;
  3. namespace UnityEngine.UI
  4. {
  5. [AddComponentMenu("UI/Loop Horizontal Scroll Rect", 50)]
  6. [DisallowMultipleComponent]
  7. public class LoopHorizontalScrollRect : LoopScrollRect
  8. {
  9. bool bInited = false;
  10. protected override float GetSize(RectTransform item)
  11. {
  12. float size = contentSpacing;
  13. if (m_GridLayout != null)
  14. {
  15. size += m_GridLayout.cellSize.x;
  16. }
  17. else
  18. {
  19. size += LayoutUtility.GetPreferredWidth(item);
  20. }
  21. return size;
  22. }
  23. protected override float GetDimension(Vector2 vector)
  24. {
  25. return vector.x;
  26. }
  27. protected override Vector2 GetVector(float value)
  28. {
  29. return new Vector2(-value, 0);
  30. }
  31. protected override void Awake()
  32. {
  33. base.Awake();
  34. directionSign = 1;
  35. GridLayoutGroup layout = content.GetComponent<GridLayoutGroup>();
  36. if (layout != null && layout.constraint != GridLayoutGroup.Constraint.FixedRowCount)
  37. {
  38. //Debug.LogError("[LoopHorizontalScrollRect] unsupported GridLayoutGroup constraint");
  39. }
  40. }
  41. protected override bool UpdateItems(Bounds viewBounds, Bounds contentBounds)
  42. {
  43. if (!bInited)
  44. {
  45. bInited = true;
  46. CalcContentCount(viewBounds);
  47. }
  48. bool changed = false;
  49. if (viewBounds.max.x > contentBounds.max.x)
  50. {
  51. float size = NewItemAtEnd();
  52. if (size > 0)
  53. {
  54. if (threshold < size)
  55. {
  56. // Preventing new and delete repeatly...
  57. threshold = size * 1.1f;
  58. }
  59. changed = true;
  60. }
  61. }
  62. else if (viewBounds.max.x < contentBounds.max.x - threshold)
  63. {
  64. float size = DeleteItemAtEnd();
  65. if (size > 0)
  66. {
  67. changed = true;
  68. }
  69. }
  70. if (viewBounds.min.x < contentBounds.min.x)
  71. {
  72. float size = NewItemAtStart();
  73. if (size > 0)
  74. {
  75. if (threshold < size)
  76. {
  77. threshold = size * 1.1f;
  78. }
  79. changed = true;
  80. }
  81. }
  82. else if (viewBounds.min.x > contentBounds.min.x + threshold)
  83. {
  84. float size = DeleteItemAtStart();
  85. if (size > 0)
  86. {
  87. changed = true;
  88. }
  89. }
  90. return changed;
  91. }
  92. void CalcContentCount(Bounds viewBounds)
  93. {
  94. if (mContentCount == 0)
  95. {
  96. LayoutElement elm = Cell.GetComponent<LayoutElement>();
  97. mContentCount = Mathf.CeilToInt(viewBounds.size.x / (elm.preferredWidth + contentSpacing));
  98. }
  99. }
  100. }
  101. }