Last active
August 2, 2024 06:28
-
-
Save Sov3rain/fe60a8b083f72320c584f9dfef33797e to your computer and use it in GitHub Desktop.
Tell the Unity Scroll Rect View to snap to the given element (top).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using UnityEngine.UI; | |
public static class ScrollRectExtensions | |
{ | |
/// <summary> | |
/// Tell the Scroll Rect View to snap to the given element (top). | |
/// </summary> | |
public static void SnapTo( | |
this ScrollRect scrollRect, | |
RectTransform target, | |
float offsetX = 0f, | |
float offsetY = 0f | |
) | |
{ | |
Canvas.ForceUpdateCanvases(); | |
Vector2 contentPosition = scrollRect.transform.InverseTransformPoint(scrollRect.content.position); | |
Vector2 newPosition = scrollRect.transform.InverseTransformPoint(target.position); | |
newPosition = new Vector2(newPosition.x + offsetX, newPosition.y + offsetY); | |
if (!scrollRect.horizontal) | |
newPosition.x = contentPosition.x; | |
if (!scrollRect.vertical) | |
newPosition.y = contentPosition.y; | |
scrollRect.content.anchoredPosition = contentPosition - newPosition; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment