unity2d如何实现当拖拽UI到正确位置后不能再被拖拽的代码
时间: 2024-05-05 10:17:54 浏览: 73
unity 从UI上拖出3D物体,(2D转3D)
感谢您的提问!以下是您需要的代码:
```
using UnityEngine;
using UnityEngine.EventSystems;
public class DragAndDrop : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
private Vector3 initialPosition;
public void OnBeginDrag(PointerEventData eventData)
{
initialPosition = transform.position;
}
public void OnDrag(PointerEventData eventData)
{
transform.position = Input.mousePosition;
}
public void OnEndDrag(PointerEventData eventData)
{
float distance = Vector3.Distance(transform.position, initialPosition);
if(distance < 50) // 50 为拖拽的容错距离
{
transform.position = initialPosition;
}
else
{
// 拖拽到正确位置后,禁止再次拖拽
GetComponent<CanvasGroup>().blocksRaycasts = false;
}
}
}
```
当拖拽到正确位置后,代码会禁止再次拖拽。希望能够帮助您!
阅读全文