using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class DragDrop : MonoBehaviour, IBeginDragHandler, IEndDragHandler, IDragHandler { private RectTransform rectTransform; private CanvasGroup canvasGroup; public static GameObject itemBeingDragged; Vector3 startPosition; Transform startParent; private void Awake() { rectTransform = GetComponent(); canvasGroup = GetComponent(); } public void OnBeginDrag(PointerEventData eventData) { Debug.Log("OnBeginDrag"); if (canvasGroup) { canvasGroup.alpha = .6f; //So the ray cast will ignore the item itself. canvasGroup.blocksRaycasts = false; startPosition = transform.position; startParent = transform.parent; transform.SetParent(transform.root); itemBeingDragged = gameObject; } } public void OnDrag(PointerEventData eventData) { if (canvasGroup) { //So the item will move with our mouse (at same speed) and so it will be consistant if the canvas has a different scale (other then 1); rectTransform.anchoredPosition += eventData.delta; } } public void OnEndDrag(PointerEventData eventData) { if (canvasGroup) { itemBeingDragged = null; if (transform.parent == startParent || transform.parent == transform.root) { transform.position = startPosition; transform.SetParent(startParent); } Debug.Log("OnEndDrag"); canvasGroup.alpha = 1f; canvasGroup.blocksRaycasts = true; } } }