本文主要是介绍重复是万恶之源(一),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
不知道为啥最近越来越懒了,能一次做完的事绝对不做第二次,最近对每次写 button 事件都要重新写它的点击事件是真的烦,果断不能忍
GetComponent<Button>().onClick.AddListener(()=> {print("这是按钮的点击事件");});
我在想有没有一次性注册完这些点击事件,后面只需要根据这个 button 的名字或者是id就ok了,刚好有时间就写一下
如图,在层次结构里有不同的Button,让我来一次性获取这些 button ,注册点击事件,下面两个脚本都挂 canvas 上,初始化
下面两个脚本 一种是通过传 id 一种是通过 传 按钮的名字,看个人喜好吧,我这默认的是传按钮的名字,id 的方法我注释了
代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MyEventArgs
{// 每个button的编号,通过 id 取值public int btnID;// 通过 btn 的名字取值public string btnName;// 每个 Button 本身public GameObject obj;
}
public class UIBtnsEvent : MonoBehaviour
{Button[] buttons;// 鼠标点击委托public delegate void ButtonClickDelegate(MyEventArgs arg);public static ButtonClickDelegate ButtonClick;/// <summary>/// 通过 id 取值/// </summary>//void Start()//{// buttons = GetComponentsInChildren<Button>();// for (int i = 0; i < buttons.Length; i++)// {// MyEventArgs arg = new MyEventArgs();// arg.id = i + 1;// arg.obj = buttons[i].gameObject;// buttons[i].onClick.AddListener(() => OnButtonClickAction(arg));// }//}/// 通过 btn 的名字取值void Start(){buttons = GetComponentsInChildren<Button>();for (int i = 0; i < buttons.Length; i++){MyEventArgs arg = new MyEventArgs();arg.btnName = buttons[i].gameObject.name;arg.obj = buttons[i].gameObject;buttons[i].onClick.AddListener(() => OnButtonClickAction(arg));}}void OnButtonClickAction(MyEventArgs arg){if (ButtonClick != null){ButtonClick(arg);}}
}
怎么用:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class BtnOnClickTest : MonoBehaviour {void Start(){// UICtrWinScript.ButtonClick += Onclick;UIBtnsEvent.ButtonClick += OnClickByName;}void OnClickByName(MyEventArgs arg){switch (arg.btnName){// 这里是你按钮的名字case "Button":print("第一个按钮");break;case "Button (1)":print("第二个按钮");break;default:break;}}/// <summary>/// 通过 id 取值的方法/// </summary>/// <param name="arg"></param>void OnClickByID(MyEventArgs arg){print(arg.btnID);switch (arg.btnID){case 1:print("button1");break;case 2:print("button2");break;default:break;}}
}
效果如下:
这篇关于重复是万恶之源(一)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!