using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using Random = UnityEngine.Random;
namespace Test.UI事件系统工具类
{
public class TestUIEventTool : MonoBehaviour
{
public GameObject _img;
public GameObject _cube;//为3D对象添加UI事件,记得为相机添加【物理射线检测】,以及场景中要有【EventSystem】。
private void Start()
{
UIEventTool.AddUIEventForGameObject(_cube)
.AddEventByEventTriggerType(EventTriggerType.PointerClick, OnCubeClick);
/*
UIEventSystemTool.AddUIEvent(_cube).AddEventDic(EventTriggerType.PointerEnter,OnCubePointerEnter);
UIEventSystemTool.AddUIEvent(_cube).AddEventDic(EventTriggerType.PointerExit,OnCubePointerExit);
*/
UIEventTool.AddUIEventForGameObject(_img)
.AddEventByEventTriggerType(EventTriggerType.PointerClick, OnImageClick);
}
private void OnCubeClick()
{
Debug.Log("Click Cube...");
_cube.GetComponent<MeshRenderer>().material.color = Random.ColorHSV();
}
private void OnImageClick()
{
Debug.Log("...Click Image");
_img.GetComponent<Image>().color = Random.ColorHSV();
}
//下面是测试移入、移出UI事件
/*
private int isEnter = 0;
private void Update()
{
switch (isEnter)
{
case 1: Debug.Log("鼠标进入");
isEnter = 0;
break;
case 2: Debug.Log("鼠标移出");
isEnter = 0;
break;
}
}
private void OnCubePointerExit()
{
isEnter = 2;
}
private void OnCubePointerEnter()
{
isEnter = 1;
}
*/
}
}
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
namespace Test.UI事件系统工具类
{
public class UIEventTool : EventTrigger
{
private readonly Dictionary<EventTriggerType, Action> _eventDic = new Dictionary<EventTriggerType, Action>();
public static UIEventTool AddUIEventForGameObject(GameObject go)
{
if (!go.TryGetComponent(out UIEventTool tool))
{
tool = go.AddComponent<UIEventTool>();
}
return tool;
}
public void AddEventByEventTriggerType(EventTriggerType ett, Action action)
{
_eventDic.TryAdd(ett, action);
}
//后续需要新的UI处理函数,就重写新的UI处理函数,自行添加
public override void OnPointerClick(PointerEventData eventData)
{
if (_eventDic.TryGetValue(EventTriggerType.PointerClick, out Action action))
{
action?.Invoke();
}
}
public override void OnPointerEnter(PointerEventData eventData)
{
if (_eventDic.TryGetValue(EventTriggerType.PointerEnter, out Action action))
{
action?.Invoke();
}
}
public override void OnPointerExit(PointerEventData eventData)
{
if (_eventDic.TryGetValue(EventTriggerType.PointerExit, out Action action))
{
action?.Invoke();
}
}
}
}