Home > Back-end >  Unity Event for drag operation
Unity Event for drag operation

Time:09-29

I was checking different unity events for dragging by mouse. I found IDragHandler interface provides a method OnDrag which is called when dragging operation occurred for any UI component(please correct me if I'm wrong). I found another method 'EventTrigger.OnDrag( PointerEventData data )' In the documentation, it is written that - "Called by the EventSystem every time the pointer is moved during dragging"

So, I used this in my unity project prescribed by the documentation below

            private void Start()
            {
                //Fetch the Event Trigger component from your GameObject
                trigger = GetComponent<EventTrigger>();
                //Create a new entry for the Event Trigger
                EventTrigger.Entry entry = new EventTrigger.Entry();
                //Add a Drag type event to the Event Trigger
                entry.eventID = EventTriggerType.Drag;
                //call the OnDragDelegate function when the Event System detects dragging
                entry.callback.AddListener((data) => OnDragDelegate((PointerEventData) data));
                //Add the trigger entry
                trigger.triggers.Add(entry);
                
            }

            void OnDragDelegate(PointerEventData data)
            {
                DragToMotion();
            }

so, OnDragDelegate() is supposed to be called when any dragging operation happens. I have a cube with a box collider and I drag my mouse over it. I checked in the inspector but found no method being called while dragging, the operations in DragToMotion() are not executed as well.

Please correct me on what I'm doing wrong. What could be the solution for this?

CodePudding user response:

You need some sort of collider on the object as well as a Physics Raycaster on your camera. I'm fairly confident that the EventTriggers are just the inspector version of the drag/pointer interfaces.

Using either should end in the same result. Instead of accessing the event trigger and adding it in code, you can add the component then set a callback on the object similar to an onclick of a button.

  • Related