unity项目防止快速连续点击按钮UI

在unity项目中我们经常遇到这种情况:当我们点击一个按钮UI后会等待网络响应或者等待资源加载,这个时候我们不希望当前界面的按钮ui还可以继续点击,否则就会出现多个按钮UI命令冲突等bug。通常这种情况都可以添加遮罩UI来解决(或者利用计时器,这里不做赘述),但是这里要分享的是另外一种方法,通过UI事件的监听脚本来实现点击一个按钮后让所有按钮UI都失效。

首先,转载一篇雨松MoMo的文章:http://www.xuanyusong.com/archives/3325

(* 转载请注明: 雨松MOMO <time>2014年10月27日 </time>于 雨松MOMO程序研究院 发表
)这篇文章方便理解ui按钮的事件监听。

一、开始创建unity项目场景

image.png

image.png
GUI是为了测试打印。

二、创建两个脚本EventTriggerListener、UIButtonTest

其中EventTriggerListener脚本和雨松MoMo文章里的基本一样,只是修改和添加了几行代码:

//下面为修改的代码
 public override void OnPointerClick(PointerEventData eventData)
    {
        
        if (onClick != null&& OnCallClick())
        {
            onClick(gameObject);
        }
    }

//下面为添加的代码
    public static bool isButtonSuo = false;  //全局的静态bool变量,用来表示ui按钮是否加锁了
    public bool isSpecialButton = false;  //表示该ui按钮是否是点击后把所有ui按钮(除了解锁按钮)都锁起来的按钮(比如开始说的进入游戏按钮)
    public bool deblocking = false;  //表示该ui按钮是不是解锁按钮(点击后把所有按钮的锁打开)

    bool OnCallClick()  
    {
        if (deblocking)
        {
            isButtonSuo = false;
        }
        if (!enabled || isButtonSuo) return false;  
        isButtonSuo = isSpecialButton;

        return true;
    }

然后是另一个脚本UIButtonTest(名字随意定义,这只是我这样起的名字)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class UIButtonTest : MonoBehaviour {

    public GameObject _suo;  //加锁按钮
    public GameObject _hello;  //“你好呀”
    public GameObject _hello1;  //“我不好”
    public GameObject _hello2;  //"哈哈哈"
    public GameObject _deblocking;  //“解锁按钮”
    public GUIText _guitext;  //GUI的text,为了方便看打印输出

    private int index = 0;  //为了方便分辨打印输出
    void Start () {
        EventTriggerListener.Get(_suo).onClick = OnclickSuo;
        EventTriggerListener.Get(_suo).isSpecialButton = true;

        EventTriggerListener.Get(_hello).onClick = OnClickHello;
        EventTriggerListener.Get(_hello1).onClick = OnClickHello;
        EventTriggerListener.Get(_hello2).onClick = OnClickHello;

        EventTriggerListener.Get(_deblocking).onClick = OnClickDelocking;
        EventTriggerListener.Get(_deblocking).deblocking = true;
    }

    void OnclickSuo(GameObject go)
    {
        _guitext.text += "--所有按钮上锁了(除了解锁按钮)--";
    }

    void OnClickHello(GameObject go)
    {
        _guitext.text = go.GetComponentInChildren<Text>().text + "++" + (++index);
    }

    void OnClickHello1(GameObject go)
    {
        _guitext.text = "你好呀!++" + (++index);
    }   

    void OnClickDelocking(GameObject go)
    {
        _guitext.text = "解锁成功--";
        index = 0;
    }
}

然后把这UIButtonTest脚本放到场景的物体身上;
记得把场景中的ui按钮和GUIText物体拖入到UIButtonTest脚本对应的public的字段中

三、最后就可以运行查看效果了

我的作品1.gif

来个大的gif图:
我的作品3.gif
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容