第一种
使用条件:
1.场景中要有EventSystem
2.脚本引用命名空间using UnityEngine.EventSystems;
3.脚本继承自MonoBehaviour
4.脚本要实现接口IBeginDragHandler,IDragHandler,IEndDragHandler(第三个接口不是必须的)
5.仅对UGUI有效,ui的image组件的RaycastTarget必须勾选上
using UnityEngine;
using UnityEngine.EventSystems;
public class Test : MonoBehaviour,IBeginDragHandler, IDragHandler,IEndDragHandler
{
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();
}
}
第二种
使用条件:
1.可用于3d物体和worldspace模式的画布
2.被拖拽的物体必须挂上碰撞器,ui的碰撞器要尽量包裹住UI同时,碰撞器的size.z不要太“厚”
using UnityEngine;
public class Test1 : MonoBehaviour
{
//偏移量
private Vector3 offset = Vector3.zero;
private float z;
private void OnMouseDown()
{
z = Vector3.Dot(transform.position