using Unity.VisualScripting; using UnityEngine; using UnityEngine.EventSystems; public class UIDragSpawner : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler { public GameObject prefabToSpawn; public Canvas canvas; private RectTransform rectTransform; private CanvasGroup canvasGroup; private GameObject dragPreview; void Awake() { rectTransform = GetComponent(); //canvasGroup = gameObject.AddComponent(); canvasGroup = gameObject.GetOrAddComponent(); } public void OnBeginDrag(PointerEventData eventData) { if (canvasGroup == null) canvasGroup = gameObject.AddComponent(); canvasGroup.alpha = 0.6f; canvasGroup.blocksRaycasts = false; dragPreview = Instantiate(gameObject, canvas.transform); dragPreview.GetComponent().blocksRaycasts = false; } public void OnDrag(PointerEventData eventData) { if (dragPreview) { dragPreview.GetComponent().position = eventData.position; } } public void OnEndDrag(PointerEventData eventData) { canvasGroup.alpha = 1f; canvasGroup.blocksRaycasts = true; if (dragPreview) Destroy(dragPreview); Ray ray = Camera.main.ScreenPointToRay(eventData.position); if (Physics.Raycast(ray, out RaycastHit hit)) { Instantiate(prefabToSpawn, hit.point, Quaternion.identity); } } }