文章转自: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("按钮点击");
}
}