Drag and Drop System

Hi all,

I’m trying to create a toolbar panel in GUI where an object can be dragged from the panel onto an object (wall, ground, etc.) in the game environment. I am thinking about using a button to represent the draggable object when in panel, then when clicked, actual object is spawned in the environment. I don’t know if that’s the best way to go but I can’t think of other ways to do it. Do you have any code/links that demonstrates something like this? Much thanks in advance.

I would strongly advise against using buttons for this. The reason for this, is because buttons only register a mouse click when the mouse is released.

You are probably going to have to use an event to simulate mousedrag of GUI elements on the screen, by simply detecting all draggable objects in the GUI, and then testing if a MouseDown has originated inside of a draggable object. Next, you need to lock the draggable object to the cursor by rendering it at the mouse’s position.

When the mouse is released with a draggable object being interacted with, you need to test the location where it was dropped. If it was not over a GUI element, it should be dropped into the scene as a GameObject. You are going to have to raycast to get it to work properly, I think. Next, you can make the object draggable by setting a property within the gameobject to notify it that it is currently under mouse control. Every frame, move the object to the raycast hit position in the world of the mouse. You can optionally set a wall on how far the player can drag the item by normalizing the hit position, and then multiplying it by the maximum radius from the player.

When the player clicks again, it should release the object, and add a rigidbody to the object in order start physics simulation.

You are going to need to do extensive work via OnGUI(), the GUI class, a few MonoBehaviors, and the Event classes in order to detect the mouse position, etc.

This is not going to be simple in the slightest bit, but it’s very doable, just very involved.

Thank you so much for the thoughtful reply. I’ll follow what u had posted. Buttons are only activated when mouse is released. You’re right!

I ran into exactly the same problem, and ended up having to visualize how the terrain painting system in Unity works, and try to duplicate it. I was initially under the mistaken impression I could use buttons as well, until I stopped, thought and had a “damn it” moment which spurred me to delete about a hundred lines of code.