事件监听方法
using UnityEngine; using System.Collections; using UnityEngine.EventSystems; using System; using UnityEngine.UI; /// <summary> /// 按钮监听 /// </summary> public class EventTriggerListener : UnityEngine.EventSystems.EventTrigger { public delegate void VoidDelegate(GameObject go); public VoidDelegate onClick; public VoidDelegate onDown; public VoidDelegate onEnter; public VoidDelegate onExit; public VoidDelegate onUp; public VoidDelegate onSelect; public VoidDelegate onUpdateSelect; public VoidDelegate onDeselect; public VoidDelegate onCancel; static public EventTriggerListener Get(GameObject go) { EventTriggerListener listener = go.GetComponent<EventTriggerListener>(); if (listener == null) listener = go.AddComponent<EventTriggerListener>(); return listener; } public override void OnPointerClick(PointerEventData eventData) { if (onClick != null) onClick(gameObject); } public override void OnPointerDown(PointerEventData eventData) { if (onDown != null) onDown(gameObject); } public override void OnPointerEnter(PointerEventData eventData) { if (onEnter != null) onEnter(gameObject); } public override void OnPointerExit(PointerEventData eventData) { if (onExit != null) onExit(gameObject); } public override void OnPointerUp(PointerEventData eventData) { if (onUp != null) onUp(gameObject); } public override void OnSelect(BaseEventData eventData) { if (onSelect != null) onSelect(gameObject); } public override void OnUpdateSelected(BaseEventData eventData) { if (onUpdateSelect != null) onUpdateSelect(gameObject); } public override void OnDeselect(BaseEventData eventData) { if (onDeselect != null) onDeselect(gameObject); } public override void OnCancel(BaseEventData eventData) { if (onCancel != null) onCancel(gameObject); } }
事件监听方法的调用
using UnityEngine; using System.Collections; using UnityEngine.UI; using DG.Tweening; /// <summary> /// 控制任务栏的显示和收回 /// </summary> namespace GameLogic.UI { public class UIImageCtrl : MonoBehaviour { [SerializeField] private Toggle TaskCtrl_tog;//任务button [SerializeField] private Dropdown DropDown;//任务button [SerializeField] private Sprite show;//按钮的图片 [SerializeField] private Sprite hide;//按钮的图片 [SerializeField] private GameObject HideShowUI;//需要隐藏的UI; void Start() { if (DropDown != null) { EventTriggerListener.Get(DropDown.gameObject).onClick += DropDownOnClick; EventTriggerListener.Get(DropDown.gameObject).onSelect += DropDownOnSelect; } } public void OnClick() { if (TaskCtrl_tog != null) { if (TaskCtrl_tog.isOn) { TaskCtrl_tog.image.sprite = hide; if (HideShowUI) { HideShowUI.SetActive(false); } } else { TaskCtrl_tog.image.sprite = show; if (HideShowUI) { HideShowUI.SetActive(true); } } } } private void DropDownOnSelect(GameObject go) { Debug.Log("下啦列表关闭"); DropDown.gameObject.GetComponent<Image>().sprite = show; } private void DropDownOnClick(GameObject go) { Debug.Log("下啦列表开启"); DropDown.gameObject.GetComponent<Image>().sprite = hide; } } }