54 lines
1.6 KiB
C#
54 lines
1.6 KiB
C#
|
|
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<RectTransform>();
|
||
|
|
//canvasGroup = gameObject.AddComponent<CanvasGroup>();
|
||
|
|
canvasGroup = gameObject.GetOrAddComponent<CanvasGroup>();
|
||
|
|
}
|
||
|
|
|
||
|
|
public void OnBeginDrag(PointerEventData eventData)
|
||
|
|
{
|
||
|
|
if (canvasGroup == null)
|
||
|
|
canvasGroup = gameObject.AddComponent<CanvasGroup>();
|
||
|
|
canvasGroup.alpha = 0.6f;
|
||
|
|
canvasGroup.blocksRaycasts = false;
|
||
|
|
|
||
|
|
dragPreview = Instantiate(gameObject, canvas.transform);
|
||
|
|
dragPreview.GetComponent<CanvasGroup>().blocksRaycasts = false;
|
||
|
|
}
|
||
|
|
|
||
|
|
public void OnDrag(PointerEventData eventData)
|
||
|
|
{
|
||
|
|
if (dragPreview)
|
||
|
|
{
|
||
|
|
dragPreview.GetComponent<RectTransform>().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);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|