Search Unity

Drag and Drop GameObject to UI Window

Discussion in 'Scripting' started by Diaonic, Nov 20, 2019.

  1. Diaonic

    Diaonic

    Joined:
    Jun 21, 2016
    Posts:
    56
    I'm trying to recreate a weight based inventory. The inventory doesn't care about slots or item counts, its entirely based on the weight of items. Ultima Online had a system like this and by dragging items within a bag it would change their Z order to render on top.

    So my question is, how do I drag a game object into a canvas window. I assume when the mouse releases it will destroy the game object and create a image representation of that object and vice versa when I drag it out of the container to game space it will create a prefab.

    Heres an example of the feature I'm trying to recreate:


    Heres the basic code I have right now that just allows me to drag a game object around game space:
    Code (CSharp):
    1.     void OnMouseDown()
    2.     {
    3.         mZCoord = Camera.main.WorldToScreenPoint(
    4.         gameObject.transform.position).z;
    5.         // Store offset = gameobject world pos - mouse world pos
    6.         mOffset = gameObject.transform.position - GetMouseAsWorldPoint();
    7.     }
    8.  
    9.     private Vector3 GetMouseAsWorldPoint()
    10.     {
    11.         // Pixel coordinates of mouse (x,y)
    12.         Vector3 mousePoint = Input.mousePosition;
    13.         // z coordinate of game object on screen
    14.         mousePoint.z = mZCoord;
    15.         // Convert it to world points
    16.         return Camera.main.ScreenToWorldPoint(mousePoint);
    17.     }
    18.  
    19.     void OnMouseDrag()
    20.     {
    21.         transform.position = GetMouseAsWorldPoint() + mOffset;
    22.     }
    23. }
    What else do I need to get this off the ground?
     
  2. Diaonic

    Diaonic

    Joined:
    Jun 21, 2016
    Posts:
    56
  3. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,748
    You can hide world space mesh of dragged object and add another object into canvas wich tracks position of wolrd space object being dragged and follows it. If released within the bag, add UI item representation to the bag and delete world space object. If released outside the bag, then delete ui object
     
  4. Sackwut

    Sackwut

    Joined:
    Nov 13, 2018
    Posts:
    5
    Have you found a solution for this? Do you want to recreate this in 2d or 3d?
    I also try to implement a ultima online inventory system in 3d, but i believe that im to rookie for stuff like this.
     
  5. Diaonic

    Diaonic

    Joined:
    Jun 21, 2016
    Posts:
    56
    I was looking to do this in a 2D setting, but I ultimately went a different route. I'd love to see an implementation of it, if you come up with a solution though.