【问题标题】:How to detect scrolling up or down in panel for Unity3d?如何检测 Unity3d 面板中的向上或向下滚动?
【发布时间】:2017-05-25 18:52:07
【问题描述】:

我想检测向上或向下滚动。应该像下面的 Windows 窗体。

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

如何在 Unity3d 的面板中检测向上或向下滚动?

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

【问题讨论】:

    标签: c# user-interface unity3d unity5 scrollrect


    【解决方案1】:

    onValueChanged 对应于 ScrollbarScrollRect。不知道您使用的是哪一个,但这里是注册到onValueChanged 事件的示例代码。您可以找到其他 UI 事件示例 here。将对其进行修改以包含此答案中的示例。

    您可能需要Scrollbar。获取原始值,在开始时将其与滚动时的当前值进行比较。您可以使用它来确定上下。这假定direction 设置为TopToBottom

    scrollBar.direction = Scrollbar.Direction.TopToBottom;
    

    滚动条:

    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);
    }
    

    【讨论】:

    • 这个或者如果你想像在帖子中那样做,你可以使用docs.unity3d.com/ScriptReference/…,但基本上你会重写 onValueChanged 所做的事情。
    • 很高兴能为您提供帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-19
    • 1970-01-01
    • 2013-05-23
    • 2019-06-30
    • 1970-01-01
    • 1970-01-01
    • 2012-01-04
    相关资源
    最近更新 更多