For dragging and dropping to work we will need to first grab the Game Object and ensure while the Game Object remains grabbed it's position reciprocates the mouse position. This will work fine for not only PC bug mobile devices as well.
First define GameObject which we will be dragging.
public GameObject selectedPiece;
Now inside Update method we will give reference to touched/clicked object and while there is a reference available to an game object(selectedPiece;) we will move that object to mouse position.
When the reference is remove, object won't move therefore dropped.
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
if(hit.transform != null)
selectedPiece = hit.transform.gameObject;
selectedPiece = null;
if (selectedPiece != null)
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
selectedPiece.transform.position = new Vector3(mousePosition.x, mousePosition.y, 0);
Post a Comment