IPointerEnterHandler – OnPointerEnter – Called when a pointer enters the object IPointerExitHandler – OnPointerExit – Called when a pointer exits the object IPointerDownHandler – OnPointerDown – Called when a pointer is pressed on the object IPointerUpHandler – OnPointerUp – Called when a pointer is released (called on the original the pressed object) IPointerClickHandler – OnPointerClick – Called when a pointer is pressed and released on the same object IBeginDragHandler – OnBeginDrag – Called on the drag object when dragging is about to begin IDragHandler – OnDrag – Called on the drag object when a drag is happening IEndDragHandler – OnEndDrag – Called on the drag object when a drag finishes IDropHandler – OnDrop – Called on the object where a drag finishes IScrollHandler – OnScroll – Called when a mouse wheel scrolls IUpdateSelectedHandler – OnUpdateSelected – Called on the selected object each tick ISelectHandler – OnSelect – Called when the object becomes the selected object IDeselectHandler – OnDeselect – Called on the selected object becomes deselected IMoveHandler – OnMove – Called when a move event occurs (left, right, up, down, ect) ISubmitHandler – OnSubmit – Called when the submit button is pressed ICancelHandler – OnCancel – Called when the cancel button is pressed
上面有各种 UGUI事件的接口,今天我们简单实现一下点击事件的封装,具体步骤如下 第一步:实现点击接口如下
using UnityEngine; using System.Collections; using UnityEngine.EventSystems; public class ClickEvent :MonoBehaviour,IPointerClickHandler{ //////这里集成UI各种事件的接口,这里只实现了鼠标点击事件 public delegate void ClickDelegate(GameObject obj); public ClickDelegate onClick; public static ClickEvent Get(GameObject obj) { ClickEvent listener = obj.GetComponent<ClickEvent>(); if (listener == null) listener = obj.AddComponent<ClickEvent>(); return listener; } public void OnPointerClick(PointerEventData eventData) { if (onClick != null) onClick(gameObject); } }第二步:给需要点击 ui 添加 tag,这里我给4个 image 添加了自定义 tag:image. 然后 image 注册事件,如下
using UnityEngine; using System.Collections; public class NeedMountScript : MonoBehaviour { // Use this for initialization void Start () { GameObject[] objs = GameObject.FindGameObjectsWithTag("image"); for (int i = 0; i < objs.Length; i++) { ClickEvent.Get(objs[i]).onClick = OnClick; } } public void OnClick(GameObject other){ Debug.Log(other.name); } }第三步:好啦,将 NeedMountScript放到任意一个面板上的物体上面就可以了(不要忘记这一步额).
效果图:
总结: 总的来说是比较简单有效的封装方法,这里之封装了点击事件,若是封装其他事情,所做的事就是在刚刚的ClickEvent实现各种事件的接口,再去NeedMountScript上面给委托添加一个方法就好啦!(好吧,我承认这命名有点坑,哈哈哈哈哈哈.)
ps:为了游戏的梦,大家一起努力吧!1!1!1!!1111111!1!!!!!1刚把得
