Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Script for droping a card in a panel

Discussion in 'Getting Started' started by joefliss, Jul 2, 2018.

  1. joefliss

    joefliss

    Joined:
    Jun 13, 2018
    Posts:
    16
    Hello.

    I'm a beginner in Unity and i'm trying to make a 2D Card Game.

    I made the script for dragging the card prefab. Now i want to drop the card on the panel when it reaches it while dragging it with the mouse. But since i'm new, i want your help in writing this script.

    I have made this panel where the card will be dropped in the canvas and added the vertical layout script component so all i want is to write a script that allows the card to become a child of this specific panel when the player drags the card in the panel and releases the mouse button.

    Thank you
     

    Attached Files:

    Last edited: Jul 2, 2018
  2. Tset_Tsyung

    Tset_Tsyung

    Joined:
    Jan 12, 2016
    Posts:
    406
    Is the card a normal game object, or is it a UI object?

    Not something I've looked into before, but without looking (only just woken up lol) you could try the following ideas.

    If the case I a UI object you could try simply try something like this in a script:
    Code (CSharp):
    1. card.recttransform.parent = panel.recttransform;
    (Please note that the syntax is wrong as I haven't had coffee yet lol. You're going to want to check that.)

    But if it's a game object I'm wondering if you could simply extract the sprite from the card object, create and child object on the panel with an image component and load the sprite into that.
     
  3. joefliss

    joefliss

    Joined:
    Jun 13, 2018
    Posts:
    16
    It's solved. It was simple. i added a condition if the card's position is in the drop panel, it will become a child of that panel.

    Code (CSharp):
    1. private Vector2 CardPosition;
    2. public int minXDA = 180;
    3. public int MAXXDA = 233;
    4.  
    5. void Update()
    6.     {
    7.         CardPosition = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
    8.     }
    9.  
    10. void OnMouseUp()
    11.     {
    12.         Debug.Log("Drag ended" + CardPosition);
    13.         if ((CardPosition.x) > minXDA && (CardPosition.x) < MAXXDA)
    14.         {
    15.             this.transform.parent = DropArea.transform;
    16.             Debug.Log("Card's Parent: " + this.transform.parent.name);
    17.             Draggable = false;
    18.         }
    19.     }
     
    Tset_Tsyung likes this.
  4. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    joefliss and Tset_Tsyung like this.