按下按钮时运行代码

本文关键字:运行 代码 按钮 | 更新日期: 2023-09-27 18:04:38

我是unity和构建游戏的新手,我使用2个按钮(增加按钮,减少按钮),我遇到的问题是按钮回调函数只被调用一次,当用户点击按钮时,而不是当按钮被按住时。如何使按钮在按下时被重复调用?

    public void IncreaseBPM()
{
    if (speed < 12) 
    {
        speed += 0.05f;
        bpmText.GetComponent<BeatTextControl> ().beats += 1;
        PlayerPrefs.SetFloat ("savedBPM", speed);
    }
}
public void DecreaseBPM()
{
    if (speed > 1.5)
    {
        speed -= 0.05f;
        bpmText.GetComponent<BeatTextControl> ().beats -= 1;
        PlayerPrefs.SetFloat ("savedBPM", speed);
    }
}

按下按钮时运行代码

Unity的Button组件没有内置此功能。您必须将您自己的Image组件作为Button推出。实现IPointerDownHandlerIPointerUpHandler接口,然后覆盖OnPointerDownOnPointerUp功能。

OnPointerDown被调用时,使用struct将被点击的对象/卷Image和当前点击的pointerId存储在List中。然后可以在Update函数中检查单击了哪个Image

如果OnPointerUp被调用,您必须检查哪个pointerId被释放,然后检查pointerId是否存在于List中,如果存在则将其删除。

我已经开始做这件事了。下面是你问题中的新脚本:

public class ButtonTest : MonoBehaviour
{
    // Use this for initialization
    void Start()
    {
        //Register to Button events
        ButtonDownRelease.OnButtonActionChanged += ButtonActionChange;
        Debug.Log("Registered!");
    }
    // Update is called once per frame
    void Update()
    {
    }
    //Un-Register to Button events
    void OnDisable()
    {
        ButtonDownRelease.OnButtonActionChanged -= ButtonActionChange;
    }

    //Will be called when there is a Button action
    void ButtonActionChange(ButtonAction buttonAction)
    {
        //Check for held down
        if (buttonAction == ButtonAction.DecreaseButtonDown)
        {
            Debug.Log("Decrease Button held Down!");
            DecreaseBPM();
        }
        if (buttonAction == ButtonAction.IncreaseButtonDown)
        {
            Debug.Log("Increase Button held Down!");
            IncreaseBPM();
        }
        //Check for release
        if (buttonAction == ButtonAction.DecreaseButtonUp)
        {
            Debug.Log("Decrease Button Released!");
        }
        if (buttonAction == ButtonAction.IncreaseButtonUp)
        {
            Debug.Log("Increase Button Released!");
        }
    }
    private void IncreaseBPM()
    {
        if (TempoController.GetComponent<Pendulum>().speed < 12)
        {
            TempoController.GetComponent<Pendulum>().speed += 0.05f;
        }
    }
    private void DecreaseBPM()
    {
        if (TempoController.GetComponent<Pendulum>().speed > 1.5)
        {
            TempoController.GetComponent<Pendulum>().speed -= 0.05f;
        }
    }
}

仔细阅读

创建一个名为ButtonDownRelease的新脚本,然后将以下代码放入其中。将ButtonDownRelease脚本附加到CanvasCanvas是你的Images/Buttons UI GameObjects的父对象。创建两个Images(增加和减少)。创建两个tags,分别称为increasedecrease,然后将Images放在右边的tag中。

注意:

如果您不想使用Image组件,您仍然可以使用Button而不是Image来完成此工作。只需选择每个Button并将标签更改为increasedecrease,然后选择每个Button下的Text组件并更改其标签increasedecrease如果您想在此脚本中使用Button组件,则必须更改ButtonText标记。此外,您必须将ButtonDownRelease附加到每个Button上,而不是像Image组件那样附加到Canvas上。

ButtonDownRelease脚本:

using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using System.Collections.Generic;
public class ButtonDownRelease : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
    List<ButtonInfo> buttonInfo = new List<ButtonInfo>();
    public delegate void ButtonActionChange(ButtonAction buttonAction);
    public static event ButtonActionChange OnButtonActionChanged;
    // Update is called once per frame
    void Update()
    {
        //Send Held Button Down events
        for (int i = 0; i < buttonInfo.Count; i++)
        {
            if (buttonInfo[i].buttonPresed == ButtonAction.DecreaseButtonDown)
            {
                dispatchEvent(ButtonAction.DecreaseButtonDown);
            }
            else if (buttonInfo[i].buttonPresed == ButtonAction.IncreaseButtonDown)
            {
                dispatchEvent(ButtonAction.IncreaseButtonDown);
            }
        }
    }
    void dispatchEvent(ButtonAction btAction)
    {
        if (OnButtonActionChanged != null)
        {
            OnButtonActionChanged(btAction);
        }
    }
    public void OnPointerDown(PointerEventData eventData)
    {
        //Debug.Log("Button Down!");
        ButtonInfo bInfo = new ButtonInfo();
        bInfo.uniqueId = eventData.pointerId;
        if (eventData.pointerCurrentRaycast.gameObject.CompareTag("increase"))
        {
            bInfo.buttonPresed = ButtonAction.IncreaseButtonDown;
            addButton(bInfo);
        }
        else if (eventData.pointerCurrentRaycast.gameObject.CompareTag("decrease"))
        {
            bInfo.buttonPresed = ButtonAction.DecreaseButtonDown;
            addButton(bInfo);
        }
    }
    public void OnPointerUp(PointerEventData eventData)
    {
        //Debug.Log("Button Down!" + eventData.pointerCurrentRaycast);
        removeButton(eventData.pointerId);
    }
    void addButton(ButtonInfo bInfo)
    {
        buttonInfo.Add(bInfo);
    }
    void removeButton(int unqID)
    {
        for (int i = 0; i < buttonInfo.Count; i++)
        {
            if (unqID == buttonInfo[i].uniqueId)
            {
                //Send Release Button Up events
                if (buttonInfo[i].buttonPresed == ButtonAction.DecreaseButtonDown)
                {
                    dispatchEvent(ButtonAction.DecreaseButtonUp);
                }
                else if (buttonInfo[i].buttonPresed == ButtonAction.IncreaseButtonDown)
                {
                    dispatchEvent(ButtonAction.IncreaseButtonUp);
                }
                buttonInfo.RemoveAt(i);
            }
        }
    }
    public struct ButtonInfo
    {
        public int uniqueId;
        public ButtonAction buttonPresed;
    }
}
public enum ButtonAction
{
    None,
    IncreaseButtonDown, IncreaseButtonUp,
    DecreaseButtonDown, DecreaseButtonUp
}

最后,如果您只使用boolean变量来执行此操作,您将遇到问题。这需要用pointerId完成,就像这个答案中提供的脚本一样,以避免移动设备上的bug。这个漏洞的一个很好的例子是,当你点击一个Image,然后释放手指在另一个GameObject上,你的布尔逻辑将中断,因为OnPointerUp不会被调用。此外,在移动设备上使用多点触控也会产生问题。

首先创建两个布尔值

bool increase = false;
bool decrease = false;

然后在函数

中设置它们
public void WhenButtonClicked()
    { increase = true; }
public void WhenOtherButtonClicked()
    { decrease = true; }

然后在同一文件中的update函数中检查:

Void update(){
   If(increase){ IncreaseBPM(); }
   Else if(decrease){ DecreaseBPM(); } 
}

关于按钮何时被释放,我找到了一个简单的答案:http://answers.unity3d.com/questions/843319/46-gui-button-onrelease.html

为按钮添加一个事件触发器组件(在事件菜单中)。从那里你可以为OnPointerUp添加一个监听器。对待它就像与OnClick相同

并创建另外两个将increase和reduce设置为false的函数!