使用条件:
1.场景中要有EventSystem
2.脚本引用命名空间using UnityEngine.EventSystems;
3.脚本继承自MonoBehaviour
4.脚本要实现接口IBeginDragHandler,IDragHandler
5.仅对UGUI有效,ui的image组件的RaycastTarget必须勾选上
using UnityEngine;
using UnityEngine.EventSystems;
public class DragDetails : MonoBehaviour, IBeginDragHandler, IDragHandler
{
private Vector3 offset;
public void OnBeginDrag(PointerEventData eventData)
{
//开始拖拽的时候记录偏移量
Vector3 v3;
RectTransformUtility.ScreenPointToWorldPointInRectangle(GetComponent<RectTransform>(),
eventData.position, eventData.enterEventCamera, out v3);
offset = transform.position - v3;
}
public void OnDrag(PointerEventData eventData)
{
transform.position = Input.mousePosition + offset;
}
//public void OnEndDrag(PointerEventData eventData)
//{
// throw new System.NotImplementedException();
//}
}