Advertisement
evelynshilosky

DragDrop - Part 31

Feb 1st, 2024
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.61 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.         canvasGroup.alpha = .6f;
  32.         //So the ray cast will ignore the item itself.
  33.         canvasGroup.blocksRaycasts = false;
  34.         startPosition = transform.position;
  35.         startParent = transform.parent;
  36.         transform.SetParent(transform.root);
  37.         itemBeingDragged = gameObject;
  38.  
  39.     }
  40.  
  41.     public void OnDrag(PointerEventData eventData)
  42.     {
  43.         //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);
  44.         rectTransform.anchoredPosition += eventData.delta;
  45.  
  46.     }
  47.  
  48.  
  49.  
  50.     public void OnEndDrag(PointerEventData eventData)
  51.     {
  52.  
  53.         itemBeingDragged = null;
  54.  
  55.         if (transform.parent == startParent || transform.parent == transform.root)
  56.         {
  57.             transform.position = startPosition;
  58.             transform.SetParent(startParent);
  59.  
  60.         }
  61.  
  62.         canvasGroup.alpha = 1f;
  63.         canvasGroup.blocksRaycasts = true;
  64.     }
  65.  
  66.  
  67.  
  68. }
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement