Drag and Drop from UI to Worldspace

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.

1 Like

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.

private void PositionElement(GameObject objectToPosition)
{
    Vector2 pos = Mouse.current.position.ReadValue();
    var worldRay = m_Camera.ScreenPointToRay(pos);
 
    RaycastHit hit;
    if (Physics.Raycast(worldRay, out hit))
    {
        objectToPosition.transform.position = hit.point;
    }
}

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.
9255693--1294575--unitymousepos.gif