How to drag objects from UI into scen

Hi guys!

I’m trying to make a 2D game where you drag different characters from a UI at bottom of the screen and drop it in the scene. I just can’t get it to work.
This is what I’ve thought I’ll do:

I have a row of buttons. When I click one of them a game object spawns at the position of the pointer (over the button, creating the illusion that you drag the game object out of the button). Then that game object is transferred to a OnMouseDrag() function and drags as usual wherever you want it.

I can make an object spawn at the button (if I use a worldspace canvas as a child of the camera). But the last part how I get the newly created object to stick to the mouse is where I’m lost.

What do you think. Is this the right way to go about it or should I do something else?

Good day @LordCalvert1977 !

You need to use this 3 functions:

ScreenToWorldPoint, mousePosition, Instantiate

You need first to get a world corrds using Mouse position and ScreenToworldPoint function.

Vector3 MousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);

Once you have this, just need to Instantiate a GameObject at that position

Instantiate(GameObject prefab, Vector3 position, Quaternion rotation);

If helped you, mark the answer as good!

Bye :smiley:

Maybe with a RaycastHit2D on some DragNDropManager object? Checking if the mouse hits something while the mouse is pressed. If it already does, ignore every other object. If it doesn’t, pick up the new object.
Then it’s only an Update() on one object.

@LordCalvert1977 I partially understood what you did.
Can you please explain me what do with the Empty game object with the Instantiate Script in it?
And for instantiation, how does it take position of the mouse?
Where did you put the script you have wrote above in your answer?
what is ‘cam’ ? is ‘cam’ a variable? if yes, then which data type??

i’m trying to do a similar thing which you are trying to do, I would glad if you helped.
Thanks in advance.