File size: 1,848 Bytes
3497d64 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
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<RectTransform>();
canvasGroup = GetComponent<CanvasGroup>();
}
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;
}
}
} |