8using System.Collections.Generic;
13 [RequireComponent(typeof(ScrollRect))]
14 [AddComponentMenu(
"UI/Extensions/UIScrollToSelection")]
19 [Header(
"[ Settings ]")]
23 private float scrollSpeed = 10f;
27 private bool cancelScrollOnInput =
false;
29 private List<KeyCode> cancelScrollKeycodes =
new List<KeyCode>();
41 get {
return scrollDirection; }
45 get {
return scrollSpeed; }
51 get {
return cancelScrollOnInput; }
55 get {
return cancelScrollKeycodes; }
65 get {
return EventSystem.current; }
70 get {
return EventSystem.current.currentSelectedGameObject; }
93 CheckIfScrollingShouldBeLocked();
94 ScrollRectToLevelSelection();
98 private void UpdateReferences()
118 private void CheckIfScrollingShouldBeLocked()
136 private void ScrollRectToLevelSelection()
149 if (selection ==
null || selection.transform.parent !=
LayoutListGroup.transform)
158 UpdateVerticalScrollPosition(selection);
161 UpdateHorizontalScrollPosition(selection);
164 UpdateVerticalScrollPosition(selection);
165 UpdateHorizontalScrollPosition(selection);
170 private void UpdateVerticalScrollPosition(RectTransform selection)
173 float selectionPosition = -selection.anchoredPosition.y - (selection.rect.height * (1 - selection.pivot.y));
175 float elementHeight = selection.rect.height;
180 float offlimitsValue = GetScrollOffset(selectionPosition, listAnchorPosition, elementHeight, maskHeight);
184 (offlimitsValue /
LayoutListGroup.rect.height) * Time.unscaledDeltaTime * scrollSpeed;
187 private void UpdateHorizontalScrollPosition(RectTransform selection)
190 float selectionPosition = -selection.anchoredPosition.x - (selection.rect.width * (1 - selection.pivot.x));
192 float elementWidth = selection.rect.width;
197 float offlimitsValue = -GetScrollOffset(selectionPosition, listAnchorPosition, elementWidth, maskWidth);
201 (offlimitsValue /
LayoutListGroup.rect.width) * Time.unscaledDeltaTime * scrollSpeed;
204 private float GetScrollOffset(
float position,
float listAnchorPosition,
float targetLength,
float maskLength)
206 if (position < listAnchorPosition + (targetLength / 2))
208 return (listAnchorPosition + maskLength) - (position - targetLength);
210 else if (position + targetLength > listAnchorPosition + maskLength)
212 return (listAnchorPosition + maskLength) - (position + targetLength);
Credit Erdener Gonenc - @PixelEnvision.