Scrollbar.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. using System;
  2. using System.Collections;
  3. using UnityEngine.Events;
  4. using UnityEngine.EventSystems;
  5. namespace UnityEngine.UI
  6. {
  7. [AddComponentMenu("UI/Scrollbar", 34)]
  8. [ExecuteAlways]
  9. [RequireComponent(typeof(RectTransform))]
  10. /// <summary>
  11. /// A standard scrollbar with a variable sized handle that can be dragged between 0 and 1.
  12. /// </summary>
  13. /// <remarks>
  14. /// The slider component is a Selectable that controls a handle which follow the current value and is sized according to the size property.
  15. /// The anchors of the handle RectTransforms are driven by the Scrollbar. The handle can be a direct child of the GameObject with the Scrollbar, or intermediary RectTransforms can be placed in between for additional control.
  16. /// When a change to the scrollbar value occurs, a callback is sent to any registered listeners of onValueChanged.
  17. /// </remarks>
  18. public class Scrollbar : Selectable, IBeginDragHandler, IDragHandler, IInitializePotentialDragHandler, ICanvasElement
  19. {
  20. /// <summary>
  21. /// Setting that indicates one of four directions the scrollbar will travel.
  22. /// </summary>
  23. public enum Direction
  24. {
  25. /// <summary>
  26. /// Starting position is the Left.
  27. /// </summary>
  28. LeftToRight,
  29. /// <summary>
  30. /// Starting position is the Right
  31. /// </summary>
  32. RightToLeft,
  33. /// <summary>
  34. /// Starting position is the Bottom.
  35. /// </summary>
  36. BottomToTop,
  37. /// <summary>
  38. /// Starting position is the Top.
  39. /// </summary>
  40. TopToBottom,
  41. }
  42. [Serializable]
  43. /// <summary>
  44. /// UnityEvent callback for when a scrollbar is scrolled.
  45. /// </summary>
  46. public class ScrollEvent : UnityEvent<float> {}
  47. [SerializeField]
  48. private RectTransform m_HandleRect;
  49. /// <summary>
  50. /// The RectTransform to use for the handle.
  51. /// </summary>
  52. public RectTransform handleRect { get { return m_HandleRect; } set { if (SetPropertyUtility.SetClass(ref m_HandleRect, value)) { UpdateCachedReferences(); UpdateVisuals(); } } }
  53. // Direction of movement.
  54. [SerializeField]
  55. private Direction m_Direction = Direction.LeftToRight;
  56. /// <summary>
  57. /// The direction of the scrollbar from minimum to maximum value.
  58. /// </summary>
  59. public Direction direction { get { return m_Direction; } set { if (SetPropertyUtility.SetStruct(ref m_Direction, value)) UpdateVisuals(); } }
  60. protected Scrollbar()
  61. {}
  62. [Range(0f, 1f)]
  63. [SerializeField]
  64. private float m_Value;
  65. /// <summary>
  66. /// The current value of the scrollbar, between 0 and 1.
  67. /// </summary>
  68. public float value
  69. {
  70. get
  71. {
  72. float val = m_Value;
  73. if (m_NumberOfSteps > 1)
  74. val = Mathf.Round(val * (m_NumberOfSteps - 1)) / (m_NumberOfSteps - 1);
  75. return val;
  76. }
  77. set
  78. {
  79. Set(value);
  80. }
  81. }
  82. /// <summary>
  83. /// Set the value of the scrollbar without invoking onValueChanged callback.
  84. /// </summary>
  85. /// <param name="input">The new value for the scrollbar.</param>
  86. public virtual void SetValueWithoutNotify(float input)
  87. {
  88. Set(input, false);
  89. }
  90. [Range(0f, 1f)]
  91. [SerializeField]
  92. private float m_Size = 0.2f;
  93. /// <summary>
  94. /// The size of the scrollbar handle where 1 means it fills the entire scrollbar.
  95. /// </summary>
  96. public float size { get { return m_Size; } set { if (SetPropertyUtility.SetStruct(ref m_Size, Mathf.Clamp01(value))) UpdateVisuals(); } }
  97. [Range(0, 11)]
  98. [SerializeField]
  99. private int m_NumberOfSteps = 0;
  100. /// <summary>
  101. /// The number of steps to use for the value. A value of 0 disables use of steps.
  102. /// </summary>
  103. public int numberOfSteps { get { return m_NumberOfSteps; } set { if (SetPropertyUtility.SetStruct(ref m_NumberOfSteps, value)) { Set(m_Value); UpdateVisuals(); } } }
  104. [Space(6)]
  105. [SerializeField]
  106. private ScrollEvent m_OnValueChanged = new ScrollEvent();
  107. /// <summary>
  108. /// Handling for when the scrollbar value is changed.
  109. /// </summary>
  110. /// <remarks>
  111. /// Allow for delegate-based subscriptions for faster events than 'eventReceiver', and allowing for multiple receivers.
  112. /// </remarks>
  113. public ScrollEvent onValueChanged { get { return m_OnValueChanged; } set { m_OnValueChanged = value; } }
  114. // Private fields
  115. private RectTransform m_ContainerRect;
  116. // The offset from handle position to mouse down position
  117. private Vector2 m_Offset = Vector2.zero;
  118. // Size of each step.
  119. float stepSize { get { return (m_NumberOfSteps > 1) ? 1f / (m_NumberOfSteps - 1) : 0.1f; } }
  120. // field is never assigned warning
  121. #pragma warning disable 649
  122. private DrivenRectTransformTracker m_Tracker;
  123. #pragma warning restore 649
  124. private Coroutine m_PointerDownRepeat;
  125. private bool isPointerDownAndNotDragging = false;
  126. // This "delayed" mechanism is required for case 1037681.
  127. private bool m_DelayedUpdateVisuals = false;
  128. #if UNITY_EDITOR
  129. protected override void OnValidate()
  130. {
  131. base.OnValidate();
  132. m_Size = Mathf.Clamp01(m_Size);
  133. //This can be invoked before OnEnabled is called. So we shouldn't be accessing other objects, before OnEnable is called.
  134. if (IsActive())
  135. {
  136. UpdateCachedReferences();
  137. Set(m_Value, false);
  138. // Update rects (in next update) since other things might affect them even if value didn't change.
  139. m_DelayedUpdateVisuals = true;
  140. }
  141. if (!UnityEditor.PrefabUtility.IsPartOfPrefabAsset(this) && !Application.isPlaying)
  142. CanvasUpdateRegistry.RegisterCanvasElementForLayoutRebuild(this);
  143. }
  144. #endif // if UNITY_EDITOR
  145. public virtual void Rebuild(CanvasUpdate executing)
  146. {
  147. #if UNITY_EDITOR
  148. if (executing == CanvasUpdate.Prelayout)
  149. onValueChanged.Invoke(value);
  150. #endif
  151. }
  152. /// <summary>
  153. /// See ICanvasElement.LayoutComplete.
  154. /// </summary>
  155. public virtual void LayoutComplete()
  156. {}
  157. /// <summary>
  158. /// See ICanvasElement.GraphicUpdateComplete.
  159. /// </summary>
  160. public virtual void GraphicUpdateComplete()
  161. {}
  162. protected override void OnEnable()
  163. {
  164. base.OnEnable();
  165. UpdateCachedReferences();
  166. Set(m_Value, false);
  167. // Update rects since they need to be initialized correctly.
  168. UpdateVisuals();
  169. }
  170. protected override void OnDisable()
  171. {
  172. m_Tracker.Clear();
  173. base.OnDisable();
  174. }
  175. /// <summary>
  176. /// Update the rect based on the delayed update visuals.
  177. /// Got around issue of calling sendMessage from onValidate.
  178. /// </summary>
  179. protected virtual void Update()
  180. {
  181. if (m_DelayedUpdateVisuals)
  182. {
  183. m_DelayedUpdateVisuals = false;
  184. UpdateVisuals();
  185. }
  186. }
  187. void UpdateCachedReferences()
  188. {
  189. if (m_HandleRect && m_HandleRect.parent != null)
  190. m_ContainerRect = m_HandleRect.parent.GetComponent<RectTransform>();
  191. else
  192. m_ContainerRect = null;
  193. }
  194. void Set(float input, bool sendCallback = true)
  195. {
  196. float currentValue = m_Value;
  197. // bugfix (case 802330) clamp01 input in callee before calling this function, this allows inertia from dragging content to go past extremities without being clamped
  198. m_Value = input;
  199. // If the stepped value doesn't match the last one, it's time to update
  200. if (currentValue == value)
  201. return;
  202. UpdateVisuals();
  203. if (sendCallback)
  204. {
  205. UISystemProfilerApi.AddMarker("Scrollbar.value", this);
  206. m_OnValueChanged.Invoke(value);
  207. }
  208. }
  209. protected override void OnRectTransformDimensionsChange()
  210. {
  211. base.OnRectTransformDimensionsChange();
  212. //This can be invoked before OnEnabled is called. So we shouldn't be accessing other objects, before OnEnable is called.
  213. if (!IsActive())
  214. return;
  215. UpdateVisuals();
  216. }
  217. enum Axis
  218. {
  219. Horizontal = 0,
  220. Vertical = 1
  221. }
  222. Axis axis { get { return (m_Direction == Direction.LeftToRight || m_Direction == Direction.RightToLeft) ? Axis.Horizontal : Axis.Vertical; } }
  223. bool reverseValue { get { return m_Direction == Direction.RightToLeft || m_Direction == Direction.TopToBottom; } }
  224. // Force-update the scroll bar. Useful if you've changed the properties and want it to update visually.
  225. private void UpdateVisuals()
  226. {
  227. #if UNITY_EDITOR
  228. if (!Application.isPlaying)
  229. UpdateCachedReferences();
  230. #endif
  231. m_Tracker.Clear();
  232. if (m_ContainerRect != null)
  233. {
  234. m_Tracker.Add(this, m_HandleRect, DrivenTransformProperties.Anchors);
  235. Vector2 anchorMin = Vector2.zero;
  236. Vector2 anchorMax = Vector2.one;
  237. float movement = Mathf.Clamp01(value) * (1 - size);
  238. if (reverseValue)
  239. {
  240. anchorMin[(int)axis] = 1 - movement - size;
  241. anchorMax[(int)axis] = 1 - movement;
  242. }
  243. else
  244. {
  245. anchorMin[(int)axis] = movement;
  246. anchorMax[(int)axis] = movement + size;
  247. }
  248. m_HandleRect.anchorMin = anchorMin;
  249. m_HandleRect.anchorMax = anchorMax;
  250. }
  251. }
  252. // Update the scroll bar's position based on the mouse.
  253. void UpdateDrag(PointerEventData eventData)
  254. {
  255. if (eventData.button != PointerEventData.InputButton.Left)
  256. return;
  257. if (m_ContainerRect == null)
  258. return;
  259. Vector2 position = Vector2.zero;
  260. if (!MultipleDisplayUtilities.GetRelativeMousePositionForDrag(eventData, ref position))
  261. return;
  262. Vector2 localCursor;
  263. if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(m_ContainerRect, position, eventData.pressEventCamera, out localCursor))
  264. return;
  265. Vector2 handleCenterRelativeToContainerCorner = localCursor - m_Offset - m_ContainerRect.rect.position;
  266. Vector2 handleCorner = handleCenterRelativeToContainerCorner - (m_HandleRect.rect.size - m_HandleRect.sizeDelta) * 0.5f;
  267. float parentSize = axis == 0 ? m_ContainerRect.rect.width : m_ContainerRect.rect.height;
  268. float remainingSize = parentSize * (1 - size);
  269. if (remainingSize <= 0)
  270. return;
  271. DoUpdateDrag(handleCorner, remainingSize);
  272. }
  273. //this function is testable, it is found using reflection in ScrollbarClamp test
  274. private void DoUpdateDrag(Vector2 handleCorner, float remainingSize)
  275. {
  276. switch (m_Direction)
  277. {
  278. case Direction.LeftToRight:
  279. Set(Mathf.Clamp01(handleCorner.x / remainingSize));
  280. break;
  281. case Direction.RightToLeft:
  282. Set(Mathf.Clamp01(1f - (handleCorner.x / remainingSize)));
  283. break;
  284. case Direction.BottomToTop:
  285. Set(Mathf.Clamp01(handleCorner.y / remainingSize));
  286. break;
  287. case Direction.TopToBottom:
  288. Set(Mathf.Clamp01(1f - (handleCorner.y / remainingSize)));
  289. break;
  290. }
  291. }
  292. private bool MayDrag(PointerEventData eventData)
  293. {
  294. return IsActive() && IsInteractable() && eventData.button == PointerEventData.InputButton.Left;
  295. }
  296. /// <summary>
  297. /// Handling for when the scrollbar value is begin being dragged.
  298. /// </summary>
  299. public virtual void OnBeginDrag(PointerEventData eventData)
  300. {
  301. isPointerDownAndNotDragging = false;
  302. if (!MayDrag(eventData))
  303. return;
  304. if (m_ContainerRect == null)
  305. return;
  306. m_Offset = Vector2.zero;
  307. if (RectTransformUtility.RectangleContainsScreenPoint(m_HandleRect, eventData.pointerPressRaycast.screenPosition, eventData.enterEventCamera))
  308. {
  309. Vector2 localMousePos;
  310. if (RectTransformUtility.ScreenPointToLocalPointInRectangle(m_HandleRect, eventData.pointerPressRaycast.screenPosition, eventData.pressEventCamera, out localMousePos))
  311. m_Offset = localMousePos - m_HandleRect.rect.center;
  312. }
  313. }
  314. /// <summary>
  315. /// Handling for when the scrollbar value is dragged.
  316. /// </summary>
  317. public virtual void OnDrag(PointerEventData eventData)
  318. {
  319. if (!MayDrag(eventData))
  320. return;
  321. if (m_ContainerRect != null)
  322. UpdateDrag(eventData);
  323. }
  324. /// <summary>
  325. /// Event triggered when pointer is pressed down on the scrollbar.
  326. /// </summary>
  327. public override void OnPointerDown(PointerEventData eventData)
  328. {
  329. if (!MayDrag(eventData))
  330. return;
  331. base.OnPointerDown(eventData);
  332. isPointerDownAndNotDragging = true;
  333. m_PointerDownRepeat = StartCoroutine(ClickRepeat(eventData.pointerPressRaycast.screenPosition, eventData.enterEventCamera));
  334. }
  335. protected IEnumerator ClickRepeat(PointerEventData eventData)
  336. {
  337. return ClickRepeat(eventData.pointerPressRaycast.screenPosition, eventData.enterEventCamera);
  338. }
  339. /// <summary>
  340. /// Coroutine function for handling continual press during Scrollbar.OnPointerDown.
  341. /// </summary>
  342. protected IEnumerator ClickRepeat(Vector2 screenPosition, Camera camera)
  343. {
  344. while (isPointerDownAndNotDragging)
  345. {
  346. if (!RectTransformUtility.RectangleContainsScreenPoint(m_HandleRect, screenPosition, camera))
  347. {
  348. Vector2 localMousePos;
  349. if (RectTransformUtility.ScreenPointToLocalPointInRectangle(m_HandleRect, screenPosition, camera, out localMousePos))
  350. {
  351. var axisCoordinate = axis == 0 ? localMousePos.x : localMousePos.y;
  352. // modifying value depending on direction, fixes (case 925824)
  353. float change = axisCoordinate < 0 ? size : -size;
  354. value += reverseValue ? change : -change;
  355. }
  356. }
  357. yield return new WaitForEndOfFrame();
  358. }
  359. StopCoroutine(m_PointerDownRepeat);
  360. }
  361. /// <summary>
  362. /// Event triggered when pointer is released after pressing on the scrollbar.
  363. /// </summary>
  364. public override void OnPointerUp(PointerEventData eventData)
  365. {
  366. base.OnPointerUp(eventData);
  367. isPointerDownAndNotDragging = false;
  368. }
  369. /// <summary>
  370. /// Handling for movement events.
  371. /// </summary>
  372. public override void OnMove(AxisEventData eventData)
  373. {
  374. if (!IsActive() || !IsInteractable())
  375. {
  376. base.OnMove(eventData);
  377. return;
  378. }
  379. switch (eventData.moveDir)
  380. {
  381. case MoveDirection.Left:
  382. if (axis == Axis.Horizontal && FindSelectableOnLeft() == null)
  383. Set(Mathf.Clamp01(reverseValue ? value + stepSize : value - stepSize));
  384. else
  385. base.OnMove(eventData);
  386. break;
  387. case MoveDirection.Right:
  388. if (axis == Axis.Horizontal && FindSelectableOnRight() == null)
  389. Set(Mathf.Clamp01(reverseValue ? value - stepSize : value + stepSize));
  390. else
  391. base.OnMove(eventData);
  392. break;
  393. case MoveDirection.Up:
  394. if (axis == Axis.Vertical && FindSelectableOnUp() == null)
  395. Set(Mathf.Clamp01(reverseValue ? value - stepSize : value + stepSize));
  396. else
  397. base.OnMove(eventData);
  398. break;
  399. case MoveDirection.Down:
  400. if (axis == Axis.Vertical && FindSelectableOnDown() == null)
  401. Set(Mathf.Clamp01(reverseValue ? value + stepSize : value - stepSize));
  402. else
  403. base.OnMove(eventData);
  404. break;
  405. }
  406. }
  407. /// <summary>
  408. /// Prevents selection if we we move on the Horizontal axis. See Selectable.FindSelectableOnLeft.
  409. /// </summary>
  410. public override Selectable FindSelectableOnLeft()
  411. {
  412. if (navigation.mode == Navigation.Mode.Automatic && axis == Axis.Horizontal)
  413. return null;
  414. return base.FindSelectableOnLeft();
  415. }
  416. /// <summary>
  417. /// Prevents selection if we we move on the Horizontal axis. See Selectable.FindSelectableOnRight.
  418. /// </summary>
  419. public override Selectable FindSelectableOnRight()
  420. {
  421. if (navigation.mode == Navigation.Mode.Automatic && axis == Axis.Horizontal)
  422. return null;
  423. return base.FindSelectableOnRight();
  424. }
  425. /// <summary>
  426. /// Prevents selection if we we move on the Vertical axis. See Selectable.FindSelectableOnUp.
  427. /// </summary>
  428. public override Selectable FindSelectableOnUp()
  429. {
  430. if (navigation.mode == Navigation.Mode.Automatic && axis == Axis.Vertical)
  431. return null;
  432. return base.FindSelectableOnUp();
  433. }
  434. /// <summary>
  435. /// Prevents selection if we we move on the Vertical axis. See Selectable.FindSelectableOnDown.
  436. /// </summary>
  437. public override Selectable FindSelectableOnDown()
  438. {
  439. if (navigation.mode == Navigation.Mode.Automatic && axis == Axis.Vertical)
  440. return null;
  441. return base.FindSelectableOnDown();
  442. }
  443. /// <summary>
  444. /// See: IInitializePotentialDragHandler.OnInitializePotentialDrag
  445. /// </summary>
  446. public virtual void OnInitializePotentialDrag(PointerEventData eventData)
  447. {
  448. eventData.useDragThreshold = false;
  449. }
  450. /// <summary>
  451. /// Set the direction of the scrollbar, optionally setting the layout as well.
  452. /// </summary>
  453. /// <param name="direction">The direction of the scrollbar.</param>
  454. /// <param name="includeRectLayouts">Should the layout be flipped together with the direction?</param>
  455. public void SetDirection(Direction direction, bool includeRectLayouts)
  456. {
  457. Axis oldAxis = axis;
  458. bool oldReverse = reverseValue;
  459. this.direction = direction;
  460. if (!includeRectLayouts)
  461. return;
  462. if (axis != oldAxis)
  463. RectTransformUtility.FlipLayoutAxes(transform as RectTransform, true, true);
  464. if (reverseValue != oldReverse)
  465. RectTransformUtility.FlipLayoutOnAxis(transform as RectTransform, (int)axis, true, true);
  466. }
  467. }
  468. }