HorizontalScrollWheelHandler.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. using UnityEngine;
  2. using UnityEngine.EventSystems;
  3. using UnityEngine.UI;
  4. /// <summary>
  5. /// Attach this to a ScrollRect GameObject to convert vertical mouse scroll wheel
  6. /// input into horizontal scrolling. Useful for horizontal card list panels.
  7. /// </summary>
  8. [RequireComponent(typeof(ScrollRect))]
  9. public class HorizontalScrollWheelHandler : MonoBehaviour, IScrollHandler
  10. {
  11. private ScrollRect _scrollRect;
  12. [Tooltip("Multiplier applied to the scroll delta. Increase for faster scrolling.")]
  13. public float scrollSpeed = 1f;
  14. private void Awake()
  15. {
  16. _scrollRect = GetComponent<ScrollRect>();
  17. }
  18. public void OnScroll(PointerEventData eventData)
  19. {
  20. if (!_scrollRect.horizontal)
  21. return;
  22. // Use Y scroll delta (mouse wheel) and apply it as horizontal movement.
  23. // Negate so scrolling down moves right (conventional direction).
  24. float delta = eventData.scrollDelta.y * scrollSpeed;
  25. float contentWidth = _scrollRect.content.rect.width;
  26. float viewportWidth = _scrollRect.viewport != null
  27. ? _scrollRect.viewport.rect.width
  28. : ((RectTransform)_scrollRect.transform).rect.width;
  29. float scrollableWidth = contentWidth - viewportWidth;
  30. if (scrollableWidth <= 0f)
  31. return;
  32. _scrollRect.horizontalNormalizedPosition =
  33. Mathf.Clamp01(_scrollRect.horizontalNormalizedPosition - delta / scrollableWidth);
  34. }
  35. }