上一篇讲了UGUI的拖拽,其实所有游戏物体都可以通过实现IDragHandler, IBeginDragHandler, IEndDragHandler的接口来实现拖拽功能,如果要实现点击功能的话就实现IPointerClickHandler的接口。
需要条件:
1、需要添加Collider;
2、需要手动添加Physic 2D Raycaster或Physic Raycaster(如果想实现2d和3d物体的点击拖拽功能,则两者都添加上;UGUI需要Graphic Raycaster组件,默认在创建canvas时自动添加)。
可以封装一个事件处理的脚本,通过注册事件来实现相应的功能:
using UnityEngine;
using UnityEngine.EventSystems;
public class EventTriggerListener : MonoBehaviour,IPointerClickHandler, IPointerDownHandler, IPointerEnterHandler,
IPointerExitHandler, IPointerUpHandler,IDragHandler
{
public delegate void VoidDelegate1(GameObject go, PointerEventData eventData);
public event VoidDelegate1 OnClick;
public event VoidDelegate1 OnDown;
public event VoidDelegate1 OnEnter;
public event VoidDelegate1 OnExit;
public event VoidDelegate1 OnUp;
public event VoidDelegate1 OnDragging;
static public EventTriggerListener Get(GameObject go)
{
EventTriggerListener listener = go.GetComponent<EventTriggerListener>();
if (listener == null) listener = go.AddComponent<EventTriggerListener>();
return listener;
}
public void OnPointerClick (PointerEventData eventData)
{
if (OnClick != null) OnClick(gameObject, eventData);
}
public void OnPointerDown(PointerEventData eventData)
{
if (OnDown != null) OnDown(gameObject, eventData);
}
public void OnPointerEnter(PointerEventData eventData)
{
if (OnEnter != null) OnEnter(gameObject, eventData);
}
public void OnPointerExit(PointerEventData eventData)
{
if (OnExit != null) OnExit(gameObject, eventData);
}
public void OnPointerUp(PointerEventData eventData)
{
if (OnUp != null) OnUp(gameObject, eventData);
}
public void OnDrag (PointerEventData eventData)
{
if(OnDragging!=null) OnDragging(gameObject,eventData);
}
}
注册事件:
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class Main : MonoBehaviour
{
public SpriteRenderer spriteRenderer;
public Image image;
private void Start()
{
EventTriggerListener.Get(spriteRenderer.gameObject).OnClick += OnClick;
EventTriggerListener.Get(image.gameObject).OnClick += OnClick;
EventTriggerListener.Get(image.gameObject).OnDragging += OnDrag;
}
void OnClick(GameObject go, PointerEventData eventData)
{
Debug.Log("OnClick:"+go.name);
}
void OnDrag(GameObject go, PointerEventData eventData)
{
Debug.Log("Drag:" + go.name);
}
}