Unity UGUI中按钮自动触发UI事件

文章转自:http://www.xuanyusong.com/archives/3760


UGUI在正常情况下,我得用手点击它才会进入我的监听方法。假如我不想点击触发,我就想在某个时间点自动触发怎么办? 其实还有个方法就是自己去调用点击监听的方法,但是有个问题,比如按钮点击的时候自身会按下 抬起 会有颜色的变化。还有就是如果 多个按钮 监听方法写了多个方法里 也就不好调用了。

下面直接上代码。

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

public class UGUI_AutoClick : MonoBehaviour
{
    public Button uiButton1;
    public Button uiButton2;
    public Image uiImage;

    void Start()
    {
        uiButton1.onClick.AddListener(this.__onClick);
        uiButton2.onClick.AddListener(this.__onClick);
    }

    void OnGUI()
    {

        if (GUI.Button(new Rect (100,100,200,200), "Auto Button"))
        {
            //调用会触发Button的按钮变色
            ExecuteEvents.Execute<ISubmitHandler>(uiButton1.gameObject, new PointerEventData(EventSystem.current), ExecuteEvents.submitHandler);
        }

        if (GUI.Button(new Rect(300, 100, 200, 200), "Auto Button"))
        {
            //调用不会触发按钮变色
            ExecuteEvents.Execute<IPointerClickHandler>(uiButton2.gameObject, new PointerEventData(EventSystem.current), ExecuteEvents.pointerClickHandler);
        }

        if (GUI.Button(new Rect(100, 300, 200, 200), "Auto Image"))
        {
            ExecuteEvents.Execute<IPointerClickHandler>(uiImage.gameObject, new PointerEventData(EventSystem.current), ExecuteEvents.pointerClickHandler);
        }

    }

    private void __onClick()
    {
        Debug.Log("按钮点击");
    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值