Unity Editor为UGUI属性面板添加事件

使用Editor脚本自动添加事件到UGUI的属性面板上

image.png

编辑器调用脚本如下

using UnityEngine;
using UnityEditor;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEditor.Events;

public class EditorHelp
{
    [MenuItem("Tools/遍历按钮添加事件参数", false, 1)]
    static void AutoAddButtonEvent()
    {
        Data data = GameObject.FindObjectOfType<Data>();

        GameObject[] selections = Selection.gameObjects;
        foreach (GameObject selection in selections)//遍历每个选中的物体
        {

            foreach (Button child in selection.GetComponentsInChildren<Button>())
            {
                //遍历子物体及孙物体
                Debug.Log(child.name);
                //创建一个UnityAction
                //设置委托执行的函数data.OnButtonClick,其中data在前面先查找到
                //<>中间为委托的参数,需要与OnButtonClick函数的参数一致
                //由于AddObjectPersistentListener必须要参数,因此这里必须要为函数设置一个参数
                UnityAction<Text> callback = new UnityAction<Text>(data.OnButtonClick);
                //获取一下需要填入的参数
                Text text = child.transform.GetChild(0).GetComponent<Text>();

                //为child这个Button添加callback监听事件
                UnityEventTools.AddObjectPersistentListener<Text>(child.onClick, callback, text);
            }
        }
    }
}

运行时的函数脚本如下:

using UnityEngine;
using UnityEngine.UI;

public class Data : MonoBehaviour
{

    void Start()
    {

    }

    public void OnButtonClick(Text text)
    {
        Debug.Log(text.text);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值