按住按钮时运行代码

2023-12-26

我是 Unity 和构建游戏的新手,我使用 2 个按钮(IncreaseButton、DecreaseButton),我遇到的问题是按钮回调函数仅在用户单击按钮时调用一次,但在按住按钮时不会调用。如何让按钮在按住时重复调用?

Code

    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's Button组件确实not内置了此功能。您必须使用以下功能推出自己的功能Image组件作为Button。实施IPointerDownHandler and IPointerUpHandler接口然后覆盖OnPointerDown and OnPointerUp功能。

When OnPointerDown被称为,使用struct存储哪个对象/体积Image被点击并且当前点击pointerId in a List。 然后您可以检查哪个Image被点击在Update功能。

If the 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脚本到Canvas The Canvas这是你的父母Images/ButtonsUI 游戏对象。创建两个Images(增加和减少)。创建两个tags called increase and decrease然后把两个Images在右边tag.

Note:

您仍然可以使用Button而不是Image如果您不想使用,则可以使其工作Image成分。只需选择每个Button并将标签更改为increase and decrease,然后选择Text每个下的组件Button并更改他们的标签increase and decrease too. 您必须更改Button's Text如果您想使用,也可以使用标签Button成分用这个脚本。另外,您还必须附上ButtonDownRelease每一个Button不至于Canvas就像你必须做的那样Image成分。

Your ButtonDownRelease script:

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就像这个答案中提供的脚本一样,以避免移动设备上的错误。此错误的一个很好的例子是当您单击Image然后在另一个游戏对象上松开手指,您的布尔逻辑将break因为OnPointerUp不会被调用。在移动设备上使用多点触控也会引起问题。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

按住按钮时运行代码 的相关文章

  • 以编程方式 Godaddy 发送的电子邮件不在“已发送邮件”文件夹中 C#.net

    我正在通过以下方式发送电子邮件ASP NET代码使用godaddy邮件服务器 邮件发送成功 但未存储在已发送邮件文件夹中 我正在使用下面的代码 SmtpClient client new SmtpClient client Host smt
  • 实体框架中的重复键异常?

    我试图捕获当我将具有给定用户名的现有用户插入数据库时 引发的异常 正如标题所说 我正在使用 EF 当我尝试将用户插入数据库时 引发的唯一异常是 UpdateException 如何提取此异常以识别其是否是重复异常或其他异常 catch Up
  • 此插件导致 Outlook 启动缓慢

    我正在使用 C NET 4 5 开发 Outlook Addin 项目 但部署后 有时 Outlook 会禁用我的插件 并显示此消息 这个插件导致 Outlook 启动缓慢 我不知道我的插件出了什么问题 这只有很少的代码 并且ThisAdd
  • C++:获取注册表值仅给出第一个字符[重复]

    这个问题在这里已经有答案了 我试图从注册表中获取字符串值 但我只得到第一个字母 HKEY hKey char gamePath MAX PATH if RegOpenKeyEx HKEY CURRENT USER L Software Bl
  • 将语句插入 SQL Server 数据库

    最近几天我试图找到这个错误 但没有成功 我正在尝试在数据库中插入一个新行 一切都很顺利 没有错误 也没有程序崩溃 My INSERT声明如下 INSERT INTO Polozaj Znesek Uporabnik Cas Kupec Po
  • 实体框架7审计日志

    我正在将一个旧项目移植到 ASP NET 5 和 Entity Framework 7 我使用数据库优先方法 DNX 脚手架 来创建模型 旧项目基于Entity Framework 4 审计跟踪是通过重写实现的SaveChanges的方法D
  • initializer_list 和默认构造函数重载决策

    include
  • 使用正则表达式匹配以“Id”结尾的单词?

    如何组合一个正则表达式来匹配以 Id 结尾的单词并进行区分大小写的匹配 试试这个正则表达式 w Id b w 允许前面的单词字符Id和 b确保Id位于单词末尾 b是字边界断言
  • 使用 Microsoft Graph 创建用户

    如何使用 Microsoft graph 创建用户 因为我在保存过程中遇到了权限失败的问题 我确实有几个问题 在图中调用创建用户 API 将在哪里创建用户 是在 Azure AD 还是其他地方 我尝试通过传递 json 和必需的标头来调用创
  • 从 ef core 的子集合中删除一些项目

    我有一个父表和子表 其中父表与子表具有一对多关系 我想删除一些子项 并且希望父项的子集合反映该更改 如果我使用删除选定的子项RemoveRange 那么子集合不会更新 如果我使用Remove从子集合中删除子集合然后 显然 它不如使用效率高R
  • 为什么在 .net 中使用 Invoke on Controls? [复制]

    这个问题在这里已经有答案了 可能的重复 为什么 NET不允许跨线程操作 https stackoverflow com questions 2896504 why net does not allow cross thread operat
  • 在 C# 中生成随机值

    如何使用以下命令生成随机 Int64 和 UInt64 值RandomC 中的类 这应该可以解决问题 这是一个扩展方法 因此您可以像调用普通方法一样调用它Next or NextDouble上的方法Random目的 public stati
  • ASP.NET Web API Swagger(Swashbuckle)重复OperationId

    I have a web api controller like below In swagger output I am having the below image And when I want to consume it in my
  • 从存储过程返回 int 值并在 ASP.NET 代码中检查它以验证登录表单

    当我多次尝试但没有得到有效结果时 使此代码运行的真实顺序是什么 SQL存储过程的代码 set ANSI NULLS ON set QUOTED IDENTIFIER ON GO ALTER PROC dbo login proc usern
  • 打破条件变量死锁

    我遇到这样的情况 线程 1 正在等待条件变量 A 该变量应该由线程 2 唤醒 现在线程 2 正在等待条件变量 B 该变量应该由线程 1 唤醒 在我使用的场景中条件变量 我无法避免这样的死锁情况 我检测到循环 死锁 并终止死锁参与者的线程之一
  • fscanf 和 EOF 中的否定扫描集

    我的文件中有一个以逗号分隔的字符串列表 姓名 1 姓名 2 姓名 3 我想跳过所有逗号来阅读这些名字 我写了以下循环 while true if fscanf file my string 1 break 然而 它总是比预期多执行一次 给定
  • Unity 2.0 和处理 IDisposable 类型(特别是使用 PerThreadLifetimeManager)

    我知道类似的问题被问过好几次 例如 here https stackoverflow com questions 987761 how do you reconcile idisposable and ioc here https stac
  • 检索 Autofac 容器以解析服务

    在 C WindowForms 应用程序中 我启动一个 OWIN WebApp 它创建另一个类 Erp 的单例实例 public partial class Engine Form const string url http 8080 49
  • Visual Studio 2015默认附加库

    当我在 VS 2015 中创建一个空项目时 它会自动将这些库放入 附加依赖项 中 kernel32 lib user32 lib gdi32 lib winspool lib comdlg32 lib advapi32 lib shell3
  • 网页执行回发时如何停止在注册表单上?

    我正在做我的最后一年的项目 其中 我在一页上有登录和注册表单 WebForm 当用户点击锚点时Sign Up下拉菜单ddlType 隐藏 和文本框 txtCustName txtEmail and txtConfirmPassword 显示

随机推荐

  • 在 ASCIIFoldingFilter 中使用静态“foldToAscii”方法

    我一直在使用 ASCII 折叠过滤器来处理变音符号 不仅适用于弹性搜索中的文档 还适用于各种其他类型的字符串 public static String normalizeText String text boolean shouldTrim
  • 单个解析服务器中的多个应用程序

    我花了整整一周的时间将 parse com 上托管的应用程序迁移到解析服务器 设法使一切完美运行 唯一的问题是让它在单个硬件上运行多个应用程序 而无需为此分配服务器应用程序它有 它会变得昂贵 我读了这个讨论 https github com
  • android 多数据源的分页库DataSource.Factory

    我有多个数据源 但只有一个DataSourceFactory 因此 所有来源都共享一个工厂 我需要每个数据源一个 DataSourceFactory 在我的应用程序中 我有多个 RecyclerViews 视图 因此有多个自定义数据源 那么
  • PHP 5.4 中删除 safe_mode 后的安全性在哪里

    我心里有一个棘手的问题 safe modePHP 5 4 中已删除 那么此删除的安全性如何 这是否意味着任何应用程序都可以执行任何程序 为此目的使用什么技术来防止此类暴力行为 本文 http ilia ws archives 18 PHPs
  • java.lang.SecurityException AWSCredentialsProvider 签名者信息不匹配

    我正在使用 2 个亚马逊提供的库 redshift jdbc42 1 2 27 1051 and aws java sdk core 1 11 600 两个库都定义了一个类AWSCredentialsProvider包装下com amazo
  • 将文件从服务器下载到 Ionic2 应用程序中

    我需要在我的中实现一个功能Ionic2用户可以将特定视频文件下载到 Ionic2 应用程序中 经检查Ionic Native部分 我发现以下插件可用 File 文件选择器 文件开启器 文件路径 但找不到诸如 cordova 插件 文件传输
  • 如何在Windows 10上更改Node JS进程名称?

    我有一个node js在 Windows 10 上运行的进程 我想更改进程的名称 以便可以获得一些性能详细信息 我尝试改变流程 标题的财产process对象但是 它不会反映在电源外壳中 我只能找到node作为进程名称 有没有其他方法可以更改
  • Exhaustive-deps 规则无法将自定义挂钩的结果识别为 React 参考

    想象一个钩子 export function useMounted const mounted React useRef
  • Spring Boot 多数据库:没有 EntityManagerFactoryBuilder 类型的合格 bean

    我们的 Spring Boot 应用程序中有两个数据库 称为源数据库和目标数据库 这是这些的配置 源配置 package com alex myapp config import javax persistence EntityManage
  • PHP 字符串类型提示 [关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心 help reopen questi
  • 如何在另一个线程完成时停止一个线程

    我有这个代码 Thread thread1 new Thread this DoSomething1 Thread thread2 new Thread this DoSomething2 thread1 Start thread2 Sta
  • OpenSSL:加密/解密例程的输入和输出缓冲区可以相同吗?

    例如 在 int EVP EncryptUpdate EVP CIPHER CTX ctx unsigned char out int outl unsigned char in int inl can out in 我只是偶然发现这个问题
  • 如何限制临时表的大小?

    我的数据库中有较大的 InnoDB 表 显然 用户能够使用 JOIN 进行 SELECT 从而生成临时的大型 因此位于磁盘上 表 有时 它们太大以至于耗尽了磁盘空间 导致各种奇怪的问题 有没有办法限制临时表的最大大小对于磁盘上的表 这样表就
  • 将参数值作为rails中的查询字符串传递给redirect_to

    这应该很简单 但我似乎找不到简单的答案 如何将当前请求中的参数值传递到redirect to 调用中 我想将一些表单值传递到 GET 重定向的查询字符串中 我想做这样的事情 redirect to thing foo gt params f
  • 查找多个 NumPy 数组的中值

    我有一个创建大约 50 个数组的 for 循环 数组的长度为 240 我试图找出计算数组每个元素的中值的最佳方法 本质上 我想获取循环中创建的每个数组的第一个元素 将它们放入列表中 然后找到中位数 然后对其他 239 个元素执行相同的操作
  • jit 会优化新对象吗

    我创建这个类是为了不可变并且具有流畅的 API public final class Message public final String email public final String escalationEmail public
  • 唤醒 Heroku 应用程序

    因此 我的 heroku NODE js 应用程序一直在运行 今天我通过我的 url 再次尝试它 但由于某种原因 它给了我一条应用程序错误消息 我阅读并登录到我的仪表板 它说该应用程序正在睡眠 我有 Heroku 的免费套餐 我知道该应用程
  • 如何删除 ExpandableListView 中父级和子级之间的特定空间

    Can you help me identify why there is a space between the group and the child In my case I want spaces between all group
  • Java矩阵运行时错误

    练习信 给定一个 m x n 元素的矩阵 m 行 n 列 按螺旋顺序返回矩阵的所有元素 例如 给定以下矩阵 1 2 3 4 5 6 7 8 9 You should return 1 2 3 6 9 8 7 4 5 给定代码 public
  • 按住按钮时运行代码

    我是 Unity 和构建游戏的新手 我使用 2 个按钮 IncreaseButton DecreaseButton 我遇到的问题是按钮回调函数仅在用户单击按钮时调用一次 但在按住按钮时不会调用 如何让按钮在按住时重复调用 Code publ