2025-04-30 17:55:20 +09:00
|
|
|
using Unity.VisualScripting;
|
|
|
|
|
using UnityEngine;
|
|
|
|
|
using UnityEngine.EventSystems;
|
|
|
|
|
|
|
|
|
|
public class UIDragSpawner : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
|
|
|
|
|
{
|
2025-05-09 10:53:08 +09:00
|
|
|
public RectTransform rectTransform;
|
|
|
|
|
public GameObject prefabToSpawn;
|
|
|
|
|
public LayerMask mask;
|
2025-04-30 17:55:20 +09:00
|
|
|
private GameObject dragPreview;
|
2025-05-09 10:53:08 +09:00
|
|
|
private CanvasGroup canvasGroup;
|
2025-04-30 17:55:20 +09:00
|
|
|
|
|
|
|
|
void Awake()
|
|
|
|
|
{
|
2025-05-09 10:53:08 +09:00
|
|
|
canvasGroup = gameObject.GetOrAddComponent<CanvasGroup>();
|
2025-04-30 17:55:20 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void OnBeginDrag(PointerEventData eventData)
|
|
|
|
|
{
|
|
|
|
|
if (canvasGroup == null)
|
|
|
|
|
canvasGroup = gameObject.AddComponent<CanvasGroup>();
|
|
|
|
|
canvasGroup.alpha = 0.6f;
|
|
|
|
|
canvasGroup.blocksRaycasts = false;
|
2025-05-09 10:53:08 +09:00
|
|
|
|
|
|
|
|
dragPreview = Instantiate(prefabToSpawn);
|
2025-04-30 17:55:20 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void OnDrag(PointerEventData eventData)
|
|
|
|
|
{
|
|
|
|
|
if (dragPreview)
|
|
|
|
|
{
|
2025-05-09 10:53:08 +09:00
|
|
|
Ray ray = Camera.main.ScreenPointToRay(eventData.position);
|
|
|
|
|
if (Physics.Raycast(ray, out RaycastHit hit, 100.0f, mask))
|
|
|
|
|
{
|
|
|
|
|
dragPreview.transform.position = hit.point;
|
|
|
|
|
}
|
2025-04-30 17:55:20 +09:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void OnEndDrag(PointerEventData eventData)
|
|
|
|
|
{
|
|
|
|
|
canvasGroup.alpha = 1f;
|
|
|
|
|
canvasGroup.blocksRaycasts = true;
|
|
|
|
|
|
2025-05-09 10:53:08 +09:00
|
|
|
if (IsPointerOverScrollRect(rectTransform))
|
|
|
|
|
{
|
2025-04-30 17:55:20 +09:00
|
|
|
Destroy(dragPreview);
|
2025-05-09 10:53:08 +09:00
|
|
|
dragPreview = null;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
public bool IsPointerOverScrollRect(RectTransform rt)
|
|
|
|
|
{
|
|
|
|
|
return RectTransformUtility.RectangleContainsScreenPoint(rt, Input.mousePosition);
|
2025-04-30 17:55:20 +09:00
|
|
|
}
|
|
|
|
|
}
|