- Home /
Unity 4.6: Drag and drop
Is it possible to make drag&drop inventory with new UI system, with new tools?
If not, is there a way to detect the event when user presses on a button? All i can do right now is detect when button is let go (using Button (script) / On Click () fuctionality), not pressed down.
(csharp code only please!)
Answer by Kiwasi · Dec 06, 2014 at 06:34 AM
Sure. Add an event trigger. Add a new event. Choose OnDrag. Add a listener that calls your Drag method. Typically a drag method would look like this.
public void Drag(){
transform.position = Input.mousePosition;
}
Edit: That method is rather hackish, there are plenty of issues with it. Here is a better one.
Add using UnityEngine.EventsSystem.
Implement the interfaces for IBeginDrag, IDragHandler and IEndDrag.
Set the mouse position as above inside the IDragHandler method.
You can also use IDropHandler to figure out what you have dropped the object on.
It will transmit the start of the drag, but not the end. So I went from there: I made couple more event triggers for "pointer enter" and "pointer up": to detect if i dragged something on to another button. It's hacky, but sort of works.
Wondering if there's a better way?
I think there is an OnDrop event or similar in the event system.
So there is a much better way. I'll edit my answer with a linked video.
Cool stuff, learned a lot. Thanks!
I've implemented something already, its a bit hacky, since i'm new to program$$anonymous$$g. I'm sure in next version I'm going to do something like you've shown.