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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice
  4. Dismiss Notice

Question Drag and Drop from UI to Worldspace

Discussion in 'UI Toolkit' started by Eneco, Aug 27, 2023.

  1. Eneco

    Eneco

    Joined:
    May 28, 2013
    Posts:
    16
    Hello,

    I'm currently getting along with the new UIToolkit and I wondering how can I enable a player to "drag" an item from the UI, and as soon as he leaves the "ui element" to have that specific counterpart as game object on his mouse and when he release the button its place on the "Ground".

    If the player doesn't wanna place it in the Gameworld, he can just move it back to the UI and the action will be canceled.

    I know that it can be done via clicking, but how to do with just dragging and dropping?
    The reason for dragging is, because I think its a bit faster to just grad it, without having the click or tap action in between, as I would also want to play it on mobile.
     
  2. RGVexed

    RGVexed

    Joined:
    Jul 14, 2015
    Posts:
    8
    Here's a quick attempt at this. As for integrating with ui toolkit, you could use

    https://docs.unity3d.com/Packages/com.unity.ui@1.0/api/UnityEngine.UIElements.MouseLeaveEvent.html
    and
    https://docs.unity3d.com/Packages/com.unity.ui@1.0/api/UnityEngine.UIElements.MouseEnterEvent.html
    to determine if the user is hovering over the ui section or not after clicking on the object in ui

    For dragging items, I use a combination of
    MouseLeaveEvent
    MouseMoveEvent
    MouseUpEvent
    MouseDownEvent
    to handle dragging.

    Code (CSharp):
    1. private void PositionElement(GameObject objectToPosition)
    2. {
    3.     Vector2 pos = Mouse.current.position.ReadValue();
    4.     var worldRay = m_Camera.ScreenPointToRay(pos);
    5.  
    6.     RaycastHit hit;
    7.     if (Physics.Raycast(worldRay, out hit))
    8.     {
    9.         objectToPosition.transform.position = hit.point;
    10.     }
    11. }
    Where m_Camera is a Camera object (I just initialize it to Camera.main on enable)
    Do note that the object you want to position should either be filtered out of the raycast or have its collider disabled.
    unitymousepos.gif
     
    Last edited: Aug 28, 2023