unity中EventTrigger组件的应用
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using DG.Tweening; using UnityEngine.Events; using UnityEngine.EventSystems; public class LeftMenuBarEvent { private static LeftMenuBarEvent leftMenuBar_this; //private LeftMenuBarEvent() //{ //} public static LeftMenuBarEvent Instance() { if (leftMenuBar_this == null) { leftMenuBar_this = new LeftMenuBarEvent(); } return leftMenuBar_this; } private bool m_state = true; private EventTrigger m_eventTrigger; public GameObject PanelName; public void StartInit(GameObject Obj) { Obj.transform.Find("LeftBarPanel/menu/_right").gameObject.SetActive(true); Obj.transform.Find("LeftBarPanel/menu/_left").gameObject.SetActive(false); } public void MouseInit(GameObject Obj) { AddTriggersListener(Obj.transform.Find("LeftBarPanel/menu").gameObject, EventTriggerType.PointerEnter, menuEnter); AddTriggersListener(Obj.transform.Find("LeftBarPanel/menu").gameObject, EventTriggerType.PointerExit,menuExit ); } /// <summary> /// 为obj添加Eventrigger监听事件 /// </summary> /// <param name="obj">添加监听的对象</param> /// <param name="eventType">添加的监听类型</param> /// <param name="action">触发的函数</param> public void AddTriggersListener(GameObject obj, EventTriggerType eventType, UnityAction<BaseEventData> action) { m_eventTrigger = obj.GetComponent<EventTrigger>(); if (m_eventTrigger == null) { m_eventTrigger = obj.AddComponent<EventTrigger>(); } if (m_eventTrigger.triggers.Count == 0) { m_eventTrigger.triggers = new List<EventTrigger.Entry>(); } //定义所要绑定的事件类型 EventTrigger.Entry entry = new EventTrigger.Entry(); //设置事件类型 entry.eventID = eventType; //定义回调函数 UnityAction<BaseEventData> callback = new UnityAction<BaseEventData>(action); //设置回调函数 entry.callback.AddListener(callback); //添加事件触发记录到GameObject的事件触发组件 m_eventTrigger.triggers.Add(entry); } private float origiValue = -160; private float endValue = 160; private void Enter(GameObject Obj) { Debug.LogError("进入"); Obj.transform.Find("LeftBarPanel/menu/_right").gameObject.SetActive(false); Obj.transform.Find("LeftBarPanel/menu/_left").gameObject.SetActive(true); Obj.transform.Find("LeftBarPanel/menu/leftmenu").transform.DOLocalMoveX(endValue, 0.5f); } private void Exit(GameObject Obj) { Debug.LogError("退出"); Obj.transform.Find("LeftBarPanel/menu/_right").gameObject.SetActive(true); Obj.transform.Find("LeftBarPanel/menu/_left").gameObject.SetActive(false); Obj.transform.Find("LeftBarPanel/menu/leftmenu").transform.DOLocalMoveX(origiValue, 0.5f); } private void menuEnter(BaseEventData arg0) { Enter(PanelName); } private void menuExit(BaseEventData arg0) { Exit(PanelName); } }