直接挂载到需要拖拽的每个对象上就可以了
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class OnTestDrag : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
private Vector3 beginPos;
private Image image;
void Start()
{
beginPos = transform.position;
image = transform.GetComponent<Image>();
}
public void OnBeginDrag(PointerEventData eventData)
{
image.raycastTarget = false;
beginPos = transform.position;
transform.SetAsLastSibling();
}
public void OnDrag(PointerEventData eventData)
{
transform.position = Input.mousePosition;
transform.localScale = new Vector3(0.8f, 0.8f, 0.8f);
OnTestDrag drag = eventData.pointerEnter.GetComponent<OnTestDrag>();
if (drag != null && drag.transform != transform)
{
transform.localScale = new Vector3(0.5f, 0.5f, 0.5f);
}
}
public void OnEndDrag(PointerEventData eventData)
{
OnTestDrag drag = eventData.pointerEnter.GetComponent<OnTestDrag>();
if (drag != null && drag.transform != transform)
{
Vector3 pos = drag.transform.position;
drag.transform.position = beginPos;
transform.position = pos;
transform.localScale = Vector3.one;
}
else
{
transform.position = beginPos;
transform.localScale = Vector3.one;
}
image.raycastTarget = true;
}
}