How to scroll to a specific element in ScrollRect with Unity UI?
None of the suggestions worked for me, the following code did
Here is the extension
using UnityEngine;
using UnityEngine.UI;
namespace BlinkTalk
{
public static class ScrollRectExtensions
{
public static Vector2 GetSnapToPositionToBringChildIntoView(this ScrollRect instance, RectTransform child)
{
Canvas.ForceUpdateCanvases();
Vector2 viewportLocalPosition = instance.viewport.localPosition;
Vector2 childLocalPosition = child.localPosition;
Vector2 result = new Vector2(
0 - (viewportLocalPosition.x + childLocalPosition.x),
0 - (viewportLocalPosition.y + childLocalPosition.y)
);
return result;
}
}
}
And here is how I used it to scroll a direct child of the content into view
private void Update()
{
MyScrollRect.content.localPosition = MyScrollRect.GetSnapToPositionToBringChildIntoView(someChild);
}
I am going to give you a code snippet of mine because I feel like being helpful. Hope this helps!
protected ScrollRect scrollRect;
protected RectTransform contentPanel;
public void SnapTo(RectTransform target)
{
Canvas.ForceUpdateCanvases();
contentPanel.anchoredPosition =
(Vector2)scrollRect.transform.InverseTransformPoint(contentPanel.position)
- (Vector2)scrollRect.transform.InverseTransformPoint(target.position);
}