How to detect scrolling up or down in panel for Unity3d?

ali Sevgi picture ali Sevgi · May 25, 2017 · Viewed 10.6k times · Source

I would like detect scrolling up or down. Should be like Windows Form below.

private void dgv_Scroll(object sender, ScrollEventArgs e)
    {
        if (e.OldValue > e.NewValue)
        {
            // here up
        }
        else
        {
            // here down
        }
    }

How to detect scrolling up or down in panel for Unity3d ?

public void OnScrollValueChanged(float value)
{
        if (?)
        {
            // here up
        }
        else
        {
            // here down
        }
}

Answer

Programmer picture Programmer · May 25, 2017

There is onValueChanged for Scrollbar and ScrollRect. Don't know which one you are using but here is a sample code to register to the onValueChanged event. You can find other UI events examples here. Will modify it to include samples from this answer.

You likely need the Scrollbar. Get the original value, on start then compare it with the current value when scrolling. You can use that to determine up and down. This assumes that the direction is set to TopToBottom.

scrollBar.direction = Scrollbar.Direction.TopToBottom;

Scrollbar:

public Scrollbar scrollBar;
float lastValue = 0;

void OnEnable()
{
    //Subscribe to the Scrollbar event
    scrollBar.onValueChanged.AddListener(scrollbarCallBack);
    lastValue = scrollBar.value;
}

//Will be called when Scrollbar changes
void scrollbarCallBack(float value)
{
    if (lastValue > value)
    {
        UnityEngine.Debug.Log("Scrolling UP: " + value);
    }
    else
    {
        UnityEngine.Debug.Log("Scrolling DOWN: " + value);
    }
    lastValue = value;
}

void OnDisable()
{
    //Un-Subscribe To Scrollbar Event
    scrollBar.onValueChanged.RemoveListener(scrollbarCallBack);
}

ScrollRect:

public ScrollRect scrollRect;

void OnEnable()
{
    //Subscribe to the ScrollRect event
    scrollRect.onValueChanged.AddListener(scrollRectCallBack);
}

//Will be called when ScrollRect changes
void scrollRectCallBack(Vector2 value)
{
    Debug.Log("ScrollRect Changed: " + value);
}

void OnDisable()
{
    //Un-Subscribe To ScrollRect Event
    scrollRect.onValueChanged.RemoveListener(scrollRectCallBack);
}