Skip to content

Instantly share code, notes, and snippets.

@Sov3rain
Last active February 12, 2021 14:20
Show Gist options
  • Save Sov3rain/fe60a8b083f72320c584f9dfef33797e to your computer and use it in GitHub Desktop.
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).
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