Skip to content

Instantly share code, notes, and snippets.

@mitay-walle
Created August 3, 2023 08:27
Show Gist options
  • Save mitay-walle/f1f107c1f3a58a758f3724d6d68777e4 to your computer and use it in GitHub Desktop.
Save mitay-walle/f1f107c1f3a58a758f3724d6d68777e4 to your computer and use it in GitHub Desktop.
Unity UI ScrollRect Snap To Transform
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace Plugins.UI.Extensions
{
public enum XYZ
{
X,
Y,
Z
}
public static class RectTransformExtensions
{
private static Vector3[] _cache = new Vector3[4];
private static Vector3[] _cache2 = new Vector3[4];
public static void SnapScrollToTransform(this ScrollRect scrollRect, RectTransform target)
{
Canvas.ForceUpdateCanvases();
Vector2 contentPosition = scrollRect.transform.InverseTransformPoint(scrollRect.content.position);
Vector2 newPosition = scrollRect.transform.InverseTransformPoint(target.position);
if (scrollRect.vertical)
{
if (IsBoundsDimensionMoreThen(scrollRect.viewport, target, XYZ.Y))
{
newPosition.y += scrollRect.viewport.rect.size.y * (1 - scrollRect.viewport.pivot.y) * 2;
newPosition.y -= target.rect.size.y * (1 - target.pivot.y);
}
else
{
newPosition.y += target.rect.size.y * (1 - target.pivot.y);
}
}
if (scrollRect.horizontal)
{
if (IsBoundsDimensionMoreThen(scrollRect.viewport, target, XYZ.X))
{
newPosition.x += scrollRect.viewport.rect.size.x * (1 - scrollRect.viewport.pivot.x) * 2;
newPosition.x -= target.rect.size.x * (1 - target.pivot.x);
}
else
{
newPosition.x += target.rect.size.x * (1 - target.pivot.x);
}
}
if (!scrollRect.horizontal)
newPosition.x = contentPosition.x;
if (!scrollRect.vertical)
newPosition.y = contentPosition.y;
scrollRect.content.anchoredPosition = contentPosition - newPosition;
}
public static bool IsBoundsDimensionMoreThen(this RectTransform left, RectTransform right, XYZ dimensoin = XYZ.Y)
{
left.GetWorldCorners(_cache);
right.GetWorldCorners(_cache2);
return _cache[2][(int)dimensoin] > _cache2[2][(int)dimensoin];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment