DEV Community

Discussion on: Simple UI Element Dragging Script in Unity C#

Collapse
 
handelo profile image
Handelo

As Matthew mentioned in the original post, all you need to do is capture an offset value on click and add that offset to the position change in the Update() method.
You can also circumvent using an Event System by inheriting from MonoBehavior and the pointer up/down handler interfaces instead of an EventTrigger.

So:

public class Draggable : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
    private bool dragging;
    private Vector2 offset;

    public void Update()
    {
        if (dragging)
        {
            transform.position = new Vector2(Input.mousePosition.x, Input.mousePosition.y) - offset;
        }
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        dragging = true;
        offset = eventData.position - new Vector2(transform.position.x, transform.position.y);
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        dragging = false;
    }
}
Enter fullscreen mode Exit fullscreen mode