How to swap gameObject during EventSystem drag?

How to swap gameObject during EventSystem drag? I am not referring to the usual selected gameObjects used on UIs.

I make use of the interfaces IBegin,IEnd,IDragHandler in conjunction with the EventSystem for dragging gameobjects through the scene.

What I want to know is, when I deactivate the gameobject I am currently dragging, how can I hot-swap it with another so I don’t have to click on it again. Right now it just looses focus.

You will need to track the drag focus yourself to do this.

Replace the StandaloneInputModule component, on your EventSystem game object, with this one:

public class DragInputModule : StandaloneInputModule
{
    static public GameObject dragFocusObject;
  
    protected override void ProcessDrag(PointerEventData pointerEvent)
    {
        if (!pointerEvent.dragging)
            dragFocusObject = null;
        if (dragFocusObject != null)
            pointerEvent.pointerDrag = dragFocusObject;
        
        base.ProcessDrag(pointerEvent);
    }
}

The important part to note is that the PointerEventData itself, contains the reference to the dragged object. This is how the dragged object reference is passed to the EventSystem.

Thought the only relevant line in this usage sample is:

DragInputModule.dragFocusObject = anotherObject;

Here’s the whole sample class anyway (at the 5 second mark, it switches the drag focus to anotherObject - it is assumed this object is an IDragHandler for the effect to be seen (I put two of these in my test scene):

public class DragMe : MonoBehaviour, IDragHandler
{
    public GameObject anotherObject;
    static public bool swapDone = false;
    private void Update()
    {
        if (DragInputModule.dragFocusObject == null)
            Debug.Log("currentDragObject is null");
        else
            Debug.Log(DragInputModule.dragFocusObject.name + " is the drag obect");
        
        if ((Time.realtimeSinceStartup > 5) && (swapDone==false))
        {
            swapDone = true;
            DragInputModule.dragFocusObject = anotherObject;
        }
    }
  
    public void OnDrag(PointerEventData data)
    {
        //do some actual drag move stuff
        transform.position += new Vector3(data.delta.x, data.delta.y, 0) * .01f;
    }    
}

Please note:

I’ve only done limited testing, but initial tests show this working.