I currently have my menu working almost perfectly except I want to enable smooth scroll snapping to each element in the menu. I currently have a script that lerps the scrollbar value to the nearest snap point when the user isn’t scrolling but although this is quite clean, it makes the user have to drag a distance bigger than is comfortable, and I just want a swipe to take them to the next one (it’s not necessary for a big swipe to take them multiple items down, but that would be nice)
Below is the script I’m using right now, and a demo I found that is exactly what I want (but it’s CSS so not really transferable):
What I want: http://codepen.io/sdras/pen/43c9d13b23bc34a85bb3a5e2ea985958
This script is attached to both the scrollbar to control the value, and the ScrollRect to get access to whether it is scrolling or not, and a static value to sync the values between instances:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class UI_SmoothScrollSnap : MonoBehaviour, IBeginDragHandler, IEndDragHandler {
public float SnapSpeed = 10;
public float ScrollVelocity;
[ShowInInspector] //I added this outside of my IDE so not sure if it's the right attribute
private bool isDragging;
public int Snaps;
public static bool Dragging;
private Scrollbar scroll;
private ScrollRect sRect;
// Use this for initialization
void Start () {
scroll = FindObjectOfType<Scrollbar> ();
sRect = FindObjectOfType<ScrollRect> ();
}
// Update is called once per frame
void Update () {
isDragging = Dragging;
if (!scroll)
return;
//ScrollVelocity = sRect.inertia.y;
if (!Dragging)
scroll.value = Mathf.Lerp (scroll.value, Mathf.Round (scroll.value * (Snaps - 1)) / (Snaps - 1), SnapSpeed * Time.deltaTime);
}
public void OnBeginDrag (PointerEventData eventData) {
Dragging = true;
}
public void OnEndDrag (PointerEventData eventData) {
Dragging = false;
}
}