2

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
        }
}
ali Sevgi
  • 23
  • 1
  • 1
  • 4

1 Answers1

7

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);
}
Programmer
  • 121,791
  • 22
  • 236
  • 328
  • This or if you want to do it like in the post, you can use https://docs.unity3d.com/ScriptReference/UI.ScrollRect-normalizedPosition.html but basically you would be rewriting what the onValueChanged does. – Everts May 25 '17 at 19:24
  • Glad I was able to help you! – Programmer May 25 '17 at 20:19
  • This doesn't work because I have the scroll bar automatically gradually scroll down if new text appeared, but I want it to stop if the user clicked on scroll bar or scrolled inside. Then OnValueChanged will trigger in either case. I want something that only triggers on the user input, not the automatic scrolling – pete Apr 08 '23 at 02:54