Skip to content

Instantly share code, notes, and snippets.

@tomkail
Created October 23, 2024 13:33
Show Gist options
  • Save tomkail/d773593499cf43a0b73f33cf1062b2b3 to your computer and use it in GitHub Desktop.
Save tomkail/d773593499cf43a0b73f33cf1062b2b3 to your computer and use it in GitHub Desktop.
Immediately begins a drag as soon as a mouse/finger down event occurs on a Unity UI object.
using UnityEngine;
using UnityEngine.EventSystems;
public class BeginDragImmediately : MonoBehavior, IInitializePotentialDragHandler, IBeginDragHandler, IDragHandler {
public void OnInitializePotentialDrag(PointerEventData eventData) {
eventData.pointerDrag = gameObject;
eventData.dragging = true;
eventData.useDragThreshold = false;
ExecuteEvents.ExecuteHierarchy(transform.gameObject, eventData, ExecuteEvents.beginDragHandler);
}
public void OnBeginDrag(PointerEventData eventData) {
// Only required if your Drag function is what sets the position of the gameobject
HandleDrag(eventData);
}
public void OnDrag(PointerEventData eventData) {
HandleDrag(eventData);
}
void HandleDrag(PointerEventData eventData) {
// Set position here
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment