I have made this unity package such that anyone can download it and use it. This is a portrait scrolling UI template. Download it, drag and drop in unity, drop the prefab in your scene for demo.
The code for this was a little bit tough to understand. This code was taken from google but is modified to suit how i want it. This is a simple portrait UI which can be scrolled by swiping towards right or left or wioth button navigation.
My thought process behind this was i want a UI that can scroll, infact, lerp smoothly towards left or right with a certain speed. It should also have button navigation which when clicked takes you to that page number.
void Update() { if(!isbuttonClick) currentItem=Mathf.RoundToInt(0-contentPanel.localPosition.x / item.rect.width + horizontalLayoutGroup.spacing); if ((scrollRect.velocity.magnitude < 200 && !isSnapped) || isbuttonClick) { scrollRect.velocity = Vector2.zero; snapSpeed += snapForce * Time.deltaTime; contentPanel.localPosition = new Vector3( Mathf.MoveTowards(contentPanel.localPosition.x, 0 - (currentItem * (item.rect.width + horizontalLayoutGroup.spacing)), snapSpeed), contentPanel.localPosition.y, contentPanel.localPosition.z); if (contentPanel.localPosition.x == s0 - (currentItem * (item.rect.width + horizontalLayoutGroup.spacing))) { isSnapped = true; isbuttonClick = false; snapSpeed = 0; } } if (scrollRect.velocity.magnitude > 200) { isSnapped = false; snapSpeed = 0; } }
This code is actually taken directly from google. But it was not scrolling how i wanted it to. The original code did the scrolling for some fixed width of the page. Hence when i used the code in my layout it used to scroll only till half of the next page. That is one of the things i fixed by adding item.rect.wiodth + spacing.
Another thing i added to this code was that when user clicks on any button on the bottom border it takes him to that page respectively. This part in its initial implementation was messed up, as in the suppose i click the 3rd button it would scroll till either of half of 2nd or 4th page. I knew somethings was missing in the scrolling code if i pressed a button.
To fix this what i did was assigned every button an id to mirror pages. Hence when a button is clicked it will take that id multiply it to the width+ spacing of the layout. This will make it scroll to the exact page that was clicked