1.使用unity内置方法 OnMouseXXX(),需要目标有碰撞体。适合2D贴图和3D场景使用。ui的拖动使用下面两种方法。
/// <summary>
/// Called when the mouse enters the GUIElement or Collider.
/// </summary>
void OnMouseEnter ()
/// <summary>
/// Called when the mouse is not any longer over the GUIElement or Collider.
/// </summary>
void OnMouseExit ()
/// <summary>
/// OnMouseDown is called when the user has pressed the mouse button while
/// over the GUIElement or Collider.
/// </summary>
void OnMouseDown ()
/// <summary>
/// OnMouseUp is called when the user has released the mouse button.
/// </summary>
void OnMouseUp ()
/// <summary>
/// OnMouseDrag is called when the user has clicked on a GUIElement or Collider
/// and is still holding down the mouse.
/// </summary>
void OnMouseDrag ()
/// <summary>
/// Called every frame while the mouse is over the GUIElement or Collider.
/// </summary>
void OnMouseOver ()
/// <summary>
/// OnMouseUpAsButton is only called when the mouse is released over
/// the same GUIElement or Collider as it was pressed.
/// </summary>
void OnMouseUpAsButton ()
//松开鼠标时,仅当鼠标在按下时所在的 Collider 上时,才调用 OnMouseUpAsButton。
2.使用EventTrigger 给ui物体添加EventTrigger,在其中选择需要的事件并添加相应的响应函数
3.通过接口实现拖拽
using UnityEngine;
using UnityEngine.EventSystems;
public class DragByInterface : MonoBehaviour, IPointerDownHandler, IDragHandler, IBeginDragHandler, IEndDragHandler
{
public void OnPointerDown (PointerEventData PointerEventData) { }
public void OnBeginDrag (PointerEventData PointerEventData) { }
public void OnDrag (PointerEventData PointerEventData) { }
public void OnEndDrag (PointerEventData PointerEventData) { }
}
补充:OnBeginDrag 和 OnEndDrag 依赖于OnDrag。
pointerEventData中包含一系列信息,包括距上一帧的偏移量,当前拖拽的物体等
var offset = pointerEventData.delta;
var dragTarget = pointerEventData.pointerDrag;