Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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) + Input Field. This part works fine.

But, when keyboard is opened, the selected field is under keyboard. Is there a way to programmatically scroll the form to bring the selected field into view?

I have tried using ScrollRect.verticalNormalizedPosition and it works fine to scroll some, however I am not able to make selected field appear where I want.

Thanks for your help !

like image 430
Florent Morin Avatar asked Jun 10 '15 19:06

Florent Morin


People also ask

How do I scroll an image in unity?

To begin, we need to add the Scroll Rect (Script) component to the panel. Keeping the panel selected, drag the image that is parented to the panel into the Content variable inside Scroll Rect (Script). By default, the image is set to have an elastic effect, which, in most cases, is quite nice.


2 Answers

I am going to give you a code snippet of mine because I feel like being helpful. Hope this helps!

protected ScrollRect scrollRect; protected RectTransform contentPanel;  public void SnapTo(RectTransform target) {     Canvas.ForceUpdateCanvases();      contentPanel.anchoredPosition =             (Vector2)scrollRect.transform.InverseTransformPoint(contentPanel.position)             - (Vector2)scrollRect.transform.InverseTransformPoint(target.position); } 
like image 118
maksymiuk Avatar answered Oct 05 '22 19:10

maksymiuk


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);     } 
like image 40
Peter Morris Avatar answered Oct 05 '22 21:10

Peter Morris