Unity Drag and Drop game
Hi, I'm doing a 2d puzzle game in unity which users drag and drop pieces into the puzzle. I wanted to ask if you guys know any good asset for drag and drop functionality .
Thanks very much
Answer by Fydar · Mar 03, 2016 at 08:01 PM
Hi @smtabatabaie I recommend you create your own drag and drop functionality.
All you need to know is how to use the UI elements Event Trigger. If you don't know how to do that then watch this: https://unity3d.com/learn/tutorials/modules/beginner/ui/ui-events-and-event-triggers (Sorry I can't explain it, but I can't through simple text messages).
This line of code will help you a lot:
gameObject.GetComponent<RectTransform>().position = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
This will set the position of a RectTranform to where the mouse is, combine it with the event trigger and this should work:
public DragDropItem : MonoBehaviour {
public bool hover = false;
public void OnEnter () {
hover = true;
}
public void OnExit () {
hover = false;
}
public void OnDrag () {
if (hover == true) {
gameObject.GetComponent<RectTransform>().position = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
}
} }
Sorry if the code is broken, I haven't tried it in Unity but I will edit it when I notice an error.
I know it's not an answer to your question but I hope it helps.
Your answer
![](https://koobas.hobune.stream/wayback/20220612070442im_/https://answers.unity.com/themes/thub/images/avi.jpg)