在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
我的作品3.gif