How to select a target in a scene while dragging an image from the UI?

I made a project where I dragged an image from the UI, put it on an object, and changed the material of the object.However, the problem I have now is that after I drag the image out of the scene, my object cannot be selected. How can I select the object in the scene while dragging?

I guess there could be several solutions but the first I would try would be to make a line trace from your mouse cursor and from the hit result get the object.