Unity UGUI 给Image添加点击事件的三种方式
程序员文章站
2022-03-03 15:46:12
Button在Image上面添加一个Button组件,将Button组件的过渡效果Transition设置为None,并挂上测试脚本组件(BtnOnClickTest.cs):BtnOnClickTest.csusing UnityEngine;using UnityEngine.UI;public class BtnOnClickTest : MonoBehaviour{ private void Awake() { GetCom......
Button
在 Image 上面添加一个 Button 组件,将 Button 组件的过渡效果 Transition 设置为 None,并挂上测试脚本组件(BtnOnClickTest.cs):
BtnOnClickTest.cs
using UnityEngine;
using UnityEngine.UI;
public class BtnOnClickTest : MonoBehaviour
{
private void Awake()
{
GetComponent<Button>().onClick.AddListener(OnClickCallBack);
}
private void OnClickCallBack()
{
Debug.Log("BtnOnClickTest OnClick");
}
}
EventTrigger
直接在 Image 上面挂上测试脚本组件(EventTriggerTest.cs):
EventTriggerTest.cs
using UnityEngine;
using UnityEngine.EventSystems;
public class EventTriggerTest : MonoBehaviour
{
private void Awake()
{
EventTrigger eventTrigger = gameObject.GetComponent<EventTrigger>();
if (eventTrigger == null)
{
eventTrigger = gameObject.AddComponent<EventTrigger>();
}
eventTrigger.AddEventTriggerListener(EventTriggerType.PointerClick, onClick);
}
private void onClick(BaseEventData data)
{
Debug.Log("EventTriggerTest OnClick");
}
}
AddEventTriggerListener 拓展方法:
public static void AddEventTriggerListener(this EventTrigger eventTrigger, EventTriggerType triggerType, UnityAction<BaseEventData> action)
{
EventTrigger.Entry entry = eventTrigger.triggers.Find((trigger) => trigger.eventID == triggerType);
if (entry == null)
{
entry = new EventTrigger.Entry() { eventID = triggerType };
eventTrigger.triggers.Add(entry);
}
entry.callback.AddListener(action);
}
ps:
EventTrigger 的事件类型 EventTriggerType 有很多,如下 :
IPointerClickHandler
直接在 Image 上面挂上测试脚本组件(IPointerTest.cs):
IPointerTest.cs
using UnityEngine;
using UnityEngine.EventSystems;
public class IPointerTest : MonoBehaviour, IPointerClickHandler
{
public void OnPointerClick(PointerEventData eventData)
{
Debug.Log("IPointerTest OnClick");
}
}
ps:
1、除了点击事件的接口 IPointerClickHandler 之外,还有很多其他的事件接口,例如:
更多关于事件接口的详细内容可查看 Unity UGUI事件接口概述
2、VS中快速实现接口的成员方法:
- 点击“显示可能的修补程序”:
- 点击“实现接口”:
- 自动实现了接口的成员方法:
本文地址:https://blog.csdn.net/fightsyj/article/details/109249661