How to scroll to a specific element in ScrollRect with Unity UI?

后端 未结 10 2270
野的像风
野的像风 2021-02-12 04:03

I built a registration form for a mobile game using Unity 5.1. To do that, I use Unity UI components: ScrollRect + Autolayout (Vertical layout) + Text (labels)

10条回答
  •  长发绾君心
    2021-02-12 04:17

    Although @maksymiuk's answer is the most correct one, as it properly takes into account anchors, pivot and all the rest thanks to InverseTransformPoint() function, it still didn't work out-of-box for me - for vertical scroller, it was changing its X position too. So I just made change to check if vertical or horizontal scroll is enabled, and not change their axis if they aren't.

    public static void SnapTo( this ScrollRect scroller, RectTransform child )
    {
        Canvas.ForceUpdateCanvases();
    
        var contentPos = (Vector2)scroller.transform.InverseTransformPoint( scroller.content.position );
        var childPos = (Vector2)scroller.transform.InverseTransformPoint( child.position );
        var endPos = contentPos - childPos;
        // If no horizontal scroll, then don't change contentPos.x
        if( !scroller.horizontal ) endPos.x = contentPos.x;
        // If no vertical scroll, then don't change contentPos.y
        if( !scroller.vertical ) endPos.y = contentPos.y;
        scroller.content.anchoredPosition = endPos;
    }
    

提交回复
热议问题