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

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

    In case anyone looking for a smooth scroll (using lerp).

    [SerializeField]
    private ScrollRect _scrollRectComponent; //your scroll rect component
    [SerializeField]
    RectTransform _container; //content transform of the scrollrect
    private IEnumerator LerpToChild(RectTransform target)
    {
        Vector2 _lerpTo = (Vector2)_scrollRectComponent.transform.InverseTransformPoint(_container.position) - (Vector2)_scrollRectComponent.transform.InverseTransformPoint(target.position);
        bool _lerp = true;
        Canvas.ForceUpdateCanvases();
    
        while(_lerp)
        {
            float decelerate = Mathf.Min(10f * Time.deltaTime, 1f);
            _container.anchoredPosition = Vector2.Lerp(_scrollRectComponent.transform.InverseTransformPoint(_container.position), _lerpTo, decelerate);
            if (Vector2.SqrMagnitude((Vector2)_scrollRectComponent.transform.InverseTransformPoint(_container.position) - _lerpTo) < 0.25f)
            {
                _container.anchoredPosition = _lerpTo;
                _lerp = false;
            }
            yield return null;
        }
    }
    

提交回复
热议问题