Advertisement
evelynshilosky

DragDrop - Part 5

Jun 2nd, 2024
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.69 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.EventSystems;
  5. using UnityEngine.UI;
  6.  
  7. public class DragDrop : MonoBehaviour, IBeginDragHandler, IEndDragHandler, IDragHandler
  8. {
  9.  
  10.    
  11.     private RectTransform rectTransform;
  12.     private CanvasGroup canvasGroup;
  13.  
  14.     public static GameObject itemBeingDragged;
  15.     Vector3 startPosition;
  16.     Transform startParent;
  17.  
  18.  
  19.  
  20.     private void Awake()
  21.     {
  22.        
  23.         rectTransform = GetComponent<RectTransform>();
  24.         canvasGroup = GetComponent<CanvasGroup>();
  25.  
  26.     }
  27.  
  28.  
  29.     public void OnBeginDrag(PointerEventData eventData)
  30.     {
  31.  
  32.         Debug.Log("OnBeginDrag");
  33.  
  34.         canvasGroup.alpha = .6f;
  35.         //So the ray cast will ignore the item itself.
  36.         canvasGroup.blocksRaycasts = false;
  37.         startPosition = transform.position;
  38.         startParent = transform.parent;
  39.         transform.SetParent(transform.root);
  40.         itemBeingDragged = gameObject;
  41.  
  42.     }
  43.  
  44.     public void OnDrag(PointerEventData eventData)
  45.     {
  46.         //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);
  47.         rectTransform.anchoredPosition += eventData.delta;
  48.  
  49.     }
  50.  
  51.  
  52.  
  53.     public void OnEndDrag(PointerEventData eventData)
  54.     {
  55.  
  56.         itemBeingDragged = null;
  57.  
  58.         if (transform.parent == startParent || transform.parent == transform.root)
  59.         {
  60.             transform.position = startPosition;
  61.             transform.SetParent(startParent);
  62.  
  63.         }
  64.  
  65.         Debug.Log("OnEndDrag");
  66.         canvasGroup.alpha = 1f;
  67.         canvasGroup.blocksRaycasts = true;
  68.     }
  69.  
  70.  
  71.  
  72. }
  73.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement