直接挂载到需要拖拽的每个对象上就可以了
![img_e372f8733d9e72383bfd978734dc09d8.png](https://i-blog.csdnimg.cn/blog_migrate/2be556fc40a3e9bbc53016003c5db13b.png)
图片.png
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;
}
}