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

后端 未结 10 2315
野的像风
野的像风 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:27

    here's the way I clamped selected object into ScrollRect

    private ScrollRect scrollRect;
    private RectTransform contentPanel;
    
    public void ScrollReposition(RectTransform obj)
    {
        var objPosition = (Vector2)scrollRect.transform.InverseTransformPoint(obj.position);
        var scrollHeight = scrollRect.GetComponent().rect.height;
        var objHeight = obj.rect.height;
    
        if (objPosition.y > scrollHeight / 2)
        {
            contentPanel.localPosition = new Vector2(contentPanel.localPosition.x,
                contentPanel.localPosition.y - objHeight - Padding.top);
        }
    
        if (objPosition.y < -scrollHeight / 2)
        {
            contentPanel.localPosition = new Vector2(contentPanel.localPosition.x,
    contentPanel.localPosition.y + objHeight + Padding.bottom);
        }
    }
    

提交回复
热议问题