Search Unity

Question Drag And Drop problem

Discussion in 'Scripting' started by ndbn, May 8, 2020.

  1. ndbn

    ndbn

    Joined:
    Jan 19, 2018
    Posts:
    13
    Hi,

    I use Unity 2019.3.13f1 and I have a little problem with Drag And Drop script.

    I hope to be clear and to write well.

    I'm doing a little card game where you choose the card and place it in a table. But the card, that are a drag item, is positioned when i move the card and doing a miss click and click drop space.
    Otherwise return at start position.

    The Card are a Button Component and runtimes are inserted as children into the Content of a Scrollrect, this Scrollrect has a Grid Layout Component.

    And Slot are a Image Component that have Grid Layout Component, children of Board that have Canvas Group Component

    Share my script:

    Drag Item:

    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using UnityEngine.EventSystems;
    4.  
    5. public class CardBehaviour : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
    6. {
    7.     Vector3 startPosition;
    8.     int orderCard;
    9.     Transform startTransform;
    10.  
    11.     public static GameObject actualCard = default;
    12.  
    13.     void Start()
    14.     {
    15.         startTransform = GameObject.Find("Content").transform;
    16.     }
    17.  
    18.     public void OnBeginDrag(PointerEventData eventData)
    19.     {
    20.         actualCard = this.transform.gameObject;
    21.         startPosition = this.transform.position;
    22.         orderCard = this.transform.GetSiblingIndex();
    23.         this.transform.SetParent(GameObject.Find("Canvas").transform);
    24.         Board.Instance.transform.GetComponent<CanvasGroup>().blocksRaycasts = false;
    25.     }
    26.  
    27.     public void OnDrag(PointerEventData eventData)
    28.     {
    29.         this.transform.position = eventData.position;
    30.     }
    31.  
    32.     public void OnEndDrag(PointerEventData eventData)
    33.     {
    34.         Board.Instance.transform.GetComponent<CanvasGroup>().blocksRaycasts = true;
    35.         if(transform.parent != startTransform.parent)
    36.         {
    37.             this.transform.SetParent(startTransform.transform);
    38.             this.transform.SetSiblingIndex(orderCard);
    39.             this.transform.position = startPosition;
    40.         }
    41.     }
    Drop Slot:

    Code (CSharp):
    1.  
    2. public void OnDrop(PointerEventData eventData)
    3.     {
    4.         if (this.transform.childCount == 0)
    5.             CardBehaviour.actualCard.transform.SetParent(this.transform);
    6.         CardBehaviour.actualCard = null;
    7.     }
     
    Last edited: May 8, 2020