Scrollview scroll position

I have a scrollview set up inside my canvas. I would like to set the position of that scroll view to a specific gameobject in the content section of the scroll view. How would I do this?

Or even just programmatically change the position of the scroll position inside of the scroll view. Thanks

You calculate the scroll value based on the ratio between element position and content height

            public RectTransform _element;

            ScrollRect scrollRect = GetComponent<ScrollRect>();
            float scrollValue = 1 + _element.anchoredPosition.y/scrollRect.content.GetHeight();
            scrollRect.verticalScrollbar.value = _scrollValue;
3 Likes

Works super fine, it’s slightly inaccurate with objects at the edges but that’s fine, thanks :slight_smile:

Unfortunately, it doesn’t work for me.
First thing, scrollRect.content.GetHeight() throws an error, so I modified line 4 :

float scrollValue = 1 + _element.anchoredPosition.y/scrollRect.content.rect.height;

Now the script is ok, but the content behaves oddly. Sometimes it works, as the desired element is visible (but the content seems “randomly” positioned vertically) ; and sometimes not, as the element remains off screen.

I must specify that my UI content is a complex spreadsheet with lines and columns, so it uses a lot of Layout components (Groups, Elements) and moreover a Content Size Fitter on the Content game object. I suspect this to be the problem, as the size of the Content may be recalculated with some delay.
Also my Canvas has a Canvas Scaler which may cause additional mess.

I will try your script with a more simple content… but I still need a solution to my own problem.

I found another solution on Stack Overflow which works well for me :

Here’s my own code, slightly modified :

RectTransform contentRt = content.GetComponent<RectTransform>();

void ScrollTo(Transform target) {
    Canvas.ForceUpdateCanvases();
    contentRt.anchoredPosition = (Vector2)scrollRect.transform.InverseTransformPoint(contentRt.position) - (Vector2)scrollRect.transform.InverseTransformPoint(target.position);
}

Be aware that this will act on both content’s x and y position.
If you want to modify only one coordinate, let’s say the vertical one, use this code instead :

RectTransform contentRt = content.GetComponent<RectTransform>();

void ScrollTo(Transform target) {
    Canvas.ForceUpdateCanvases();
    Vector2 offset = (Vector2)scrollRect.transform.InverseTransformPoint(contentRt.position) - (Vector2)scrollRect.transform.InverseTransformPoint(target.position);
    Vector2 anchor = contentRt.anchoredPosition;
    anchor.y = offset.y;
    contentRt.anchoredPosition = anchor;
}

For the horizontal version, simply replace y by x on line 7.

1 Like