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

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

    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);
        }
    

提交回复
热议问题