Here's a really simple video on something that is extremely useful! Inventories, Skill Bars, etc. Play 7 Awesome Games (Action, Strategy, Management) and Help Support the Channel! Get the Game Bundle 67% off unitycodemonkey.com/gameBundle.php
@CodeMonkey, hey! Thanks for this! Can you help? eventData.pointerDrag.GetComponent().anchoredPosition = GetComponent().anchoredPosition; dont work in Grid Layot Group. How fix it?
That's great , I would like to know how to allow a dragged object to remain locked once it is on its correct position so that one cannot be allowed to move it again.
If anyone is finding this video (because CM is amazing and you should be finding them) and trying to do this with the new Input system. Go to your camera and add a Physics Raycaster OR Physics 2D raycaster to your camera first. Then the events they are showing you will work. (If not using UI, I believe you may need to add a collider to the object) Hope this helps someone!
Thank you CodeMonkey as always! I made a slightly different variation that uses Triggers for the itemSlot to talk with the DragDrop class to tell it where to place the item if any part of the item enters the ItemSlot rather than just the mouse cursor. It's really awesome seeing your way of doing it, and discovering another way of doing it to fit my specific desires!
Thank you for the tutorial. It's very concise and helpful. A small tip: you don't need to add a canvas group to block raycasts for the dragged object, just grab its image component and set raycastTarget = false;
in case any other UI noobs out there run into the same issue... my console wasn't showing any click event debug messages-- the problem was i tried to make my own canvas by making an Empty and adding a Canvas component to it -- which is not the right way to go about it. : ) To solve this, go to the hierarchy and right click > UI > Canvas. This will generate a good Canvas with a graphic raycaster, and an Event System, both of which are needed for these scripts to work as shown!
You can also add a solo Event System from right click > UI > Event System if yours is missing for some reason. (When you copy paste a canvas from a different scene for example :))
Tip: by default unity has a threshold on drag, meaning the object starts following after the mouse has moved an amount in some direction. To avoid this and have the object move exactly under where you click, you need to implement the *IInitializePotentialDragHandler* interface and inside *OnInitializePotentialDrag* set *eventData.useDragThreshold = false*
I was going crazy trying to figure out why there is such a delay/lag when I drag even using the script exactly. I added IInitializePotentialDragHandler public class DragnDrop : MonoBehaviour, IPointerDownHandler, IBeginDragHandler, IEndDragHandler, IDragHandler, IInitializePotentialDragHandler and public void OnInitializePotentialDrag(PointerEventData eventData) { eventData.useDragThreshold = false; } But that didn't fix the problem sadly. Is this what you meant with your advice? Thanks!
Thank you so much for making this video. I've been going crazy for an hour trying to get OnDrop events to trigger by messing with Override Sort Order, but what I really needed to do was add a CanvasGroup and blockRaycasts as per your video. THANK YOU!
If you are using the new Unity Input Sytem this wont work by default. You need to go to Edit --> Project Settings --> Player --> Other Settings --> Change the setting "Active Input Handling" to both.
This is maybe the best tutorial I've ever come across. It feels like the guy is an actual expert, rather than just a hobbies who decided to try putting up a few videos. I learnt a tonne, including how to use the EventSystem properly. (I've been adding colliders that I don't really need.) Really good work.
Man, I had troubles getting DragDrop to work properly especially when I get into the NRE, long before I found this tutorial and adapted it to my code and made it work just the way I wanted. Thanks, Code Monkey.
This helped me a lot. I've followed some guides and most of them just turn raycastTarget as false during dragging. It never worked for me, because I've added a text field to the image. If your objects also have other components, like a text field, you need to prevent the canvas group from blocking raycasts.
Hi Codemonkey I have a problem, I have done everything exactly as in your video but my item goes too far over the mouse, even tho i have the: rectTransform.anchoredPosition += eventdata.delta / canvas.scaleFactor; No errors and it works, but only this little bit doesnt(i also have debug.log done and it triggers the event)
Using those interfaces is really neat! Thanks a ton for this amazing tutorial 👏🏻 To implement a whole drag n drop inventory is a hell of a project but it so much worth it once it is up and running. 😎
Hello I'm very new to unity and I'm trying to make a drag and drop system for a card game. I keep getting stuck when the "canvasGroup.blocksRaycasts = false;" doesn't work. The "blocksRaycasts" section is always marked as an error with the ID CS1061. I have no idea how to resolve this. Thank you!
Great tutorial! Just a quick editor bug that I discovered. If the editor is not focused (i.e. you tabbed out and back in) the scale factor of the canvas is incorrect. In my specific case, I have my editor set to play in Unfocused mode which caused this particular error. If you focus the editor by clicking anywhere, then drag the object, it will work. (edit): As an aside, this video helped me setup my UI and its customization to exactly how I wanted. So quick and easy! Thank you again!!!
I never realized these were built in events -_- I feel so dumb, I find myself brainstorming how to do things at work some days and create these huge complicated ways of accomplishing things that could of been done much simpler lol
Thank you for the tutorial. This works fine if these UI objects are only children of the canvas. If they are children of anything within the canvas, their positions are offset; the more parents they have, the bigger the offset. Not sure how to fix the offset, but any suggestions would be great. *Edit: found a solution, using a panel and having that as a child of a canvas works. I was using just an image as a panel as I didn't really see the use for the panel, but now I know.
Had the same issue, expected the anchor position to update - PosX and PosY are what get updated. Replace eventData.pointerDrag.GetComponent().anchoredPosition = this.GetComponent().anchoredPosition; With eventData.pointerDrag.transform.position = this.transform.position; Then the anchor position and layers of objects doesn't seem to matter.
Solved: Can't get it to work for me. I have the exact same code setup as you do up to 4:50, but absolutely nothing is showing up in the console debug and the drag/drop function doesn't work at all. I've tried deleting the script component and creating it all again and using it on different assets, but still nothing. Any ideas?
You don't even see the OnPointerDown? Is the script attached to the object? Does you have an EventSystem in your scene? Does your Canvas have the default setup with the Graphics Raycaster?
@@CodeMonkeyUnity Okay, you got me in the right direction! I did not have an EventSystem added, and I needed to get a 2d Raycaster on my camera and a collider on my object. Then it started registering inputs and printing to the console. The movement scale is way off still (1 pixel on screen = about .5 units of transform), but it seems like there's some background stuff for me to learn with the scaler that will help address this. Thank you so much!
Excellent explanation! Thank you for sharing!! My snapping worked using GetComponent.position instead of GetComponent().anchoredPosition... Is there any way to compare if the Obj is not on ItemSlot would be transformed to its initial position? For example, if I drop the draggable obj in another position in the scene that is not the ITemSlot, I want the draggable obj set to its initial position.
Sorting order for UI elements is based on position in the hierarchy, drag that object to "lower" in the hierarchy to make it render after which will put it on top. Through code you can use transform.SetAsLastSibling();
Thanks for the great overview. Instead of adding the CanvasGroup you can just use the Image component of the dragged item and write: "_image.raycastTarget = false;" (at least in Unity 2022, haven't tested older versions but it should work as well)
I am trying to use this on my World Space Canvas. I build something like a click-adventure. I don't want to interact with my Inventory UI right now, I want to interact with the world, so the position of my interactable objects need to be constant). Sadly my mouse moves way faster (I assume ~1.5x faster ) than my Item, when dragging. I don't know why. "canvas.scaleFactor" seems to not have an effect on my World Space Canvas. Every Child and Parent Scale is 1. My World Space Canvas has a Scale of 0.01 I have no idea how to fix that, does anyone have an idea?
I have been trying today. I have a pan and zoom script that adjusts an orthographic camera on my World Space Canvas. I found out that the camera size has a major impact on how it moves. But I have not figured out how to use this to correct the movement. Edit1: I thought I figured it out but when I exported the game and tested it as webgl, there still seems to be a secret scale factor.
@@joerideman I am not really up-to-date anymore on that topic, but maybe you should check the Canvas scale and also if any parent object have a different scale but 1.
You have to divide every parent of your parent. For example, if you have a item container as a parent of your item you have to do: rectTransform.anchoredPosition += eventData.delta / canvas.scaleFactor / itemcontainer.transform.localScale;
Code Monkey That was a Great Tutorial, but i just wanna ask what is the type of data that stands in that "eventData.pointerDrag", like the name of the object or something?
i had so many problems using anchored position cause the canva scale reference resolution sometimes does not match the player screen resolution and then eventData delta returned a wrong delta.. i fixed it using transform.position instead of rectTransform.achoredPosition.
Is there a way to make it so that once the item has to be in a slot and cannot be anchored somewhere random in the scene? So if the item is not in a slot, then it goes back to the first slot
Nice and easy, great tutorial, thank you very much. I find it quite outrageous, that such things are not available out-of-the-box. This would be the base functionality for creating virtual board games, like chess. Unity is a good engine but has the weirdest holes in its basic functionality.
I have a inventory system where each slot object has a background image and a child item image. When I drag the item image of a slot over others slot that are rendered before the source slot in the hierarchy the image just go behind the background image of those slots. Should I just make a seperate canvas for each item image or is there a better way to solve this
If this isn't outdated, this will be _exactly_ what I need for what I'm doing right now. ...great, the object I want to move is an object without a Rect Transform component. Nevermind, I fixed it by realizing that I didn't need an empty object to hold multiple objects and could instead use the background image as the parent to everything else, and move the scripts on the empty parent to the image.
If the script extends MonoBehaviour and is attached to a Game Object that is enabled then it has to work. So you probably just didn't add the script to a game object
Months ago i wanted to implement this system, but i had problem with scrollable ui. Basically if you wanted to scroll, you had to drag ui vetrically and drag in others directions, when u wanted to drag object out. But this was much time consuming, so i implemented buy button instead. :D
I have a scrollable ui inside of which is the object I want players to be able to drag and yeah... It just doesn't seem to work. When I drag the object it jitters around the center of the screen and that's about it.
Very great tutorial. Btw what outro music is it in the end of the videos? It's just one question that one of my friends asked. Here's mine: Have you attended any course before/while/after jumping into game development related to it?
Not sure the exact name, its from the RUclips music library. Most of what I know is from just learning in my own time, many years spent googling and building things, I did go to college for a year but never completed it.
@@CodeMonkeyUnity Thank you very much for your response. College is a good thing, but there are cases when it's just unnecessary. Anyway, keep up the good work!
Just store the original position and rotation of the object in variables. And if the item is not dropped in a slot you can then just reset the current position and rotation to your stored variables.
As always with this guy, these videos work to a point and then I need to find someone better to show how to actually get it working. Guessing it's just out of date info. But it's a consistent issue
Long shot asking a question a year after publication, but... So i replicated code @ 2:20, and the consol do not return any event, i assumed it was because i was pushing it to a 3d object so i created a simple 2d sprite and consol still do no return a event. only outlier i can think of, i do not have a "event System in my sampleScene, i am not sure what it is or how to add it to the project. (i assume that the main reason why my code do not work)
Everything works but whether or not OnDrop triggers is really inconsistent. Does the object utilizing OnDrop need to be under your mouse, or under the origin of the object being dropped?
For those who try this for your 3D Game: Pointer functions work only for UI Elements. If you want to use it on 3D Object you need to use "public void OnMouseDown()". Correct me If I'm wrong but this is the only solution that worked for me. :)
You can also use a Physics Raycaster instead of a Graphics Raycaster on the EventSystem. Doing that will make these functions trigger on world objects if they have Physics colliders.
how I can make the object reset his position back to the original on EndofDrag?I can figure this out, I tried with: public Vector3 startpos; on Start: startpos = transform.position; and on EndofDrag transform.position = startpos;....but not working
Here's a really simple video on something that is extremely useful! Inventories, Skill Bars, etc.
Play 7 Awesome Games (Action, Strategy, Management) and Help Support the Channel!
Get the Game Bundle 67% off unitycodemonkey.com/gameBundle.php
@CodeMonkey, hey! Thanks for this! Can you help? eventData.pointerDrag.GetComponent().anchoredPosition = GetComponent().anchoredPosition; dont work in Grid Layot Group. How fix it?
That's great , I would like to know how to allow a dragged object to remain locked once it is on its correct position so that one cannot be allowed to move it again.
@@lexmakes Try to use eventData.pointerDrag.GetComponent().position = GetComponent().position; work for me
better you use transform.position = Input.mousePosition;
then you don't need to worry about canvas scaling etc.
@@DjagoMorshosties Thank you, saved some of my hair from being rippedout.
This 10 minute video saved me probably three hours worth of effort, thank you very much.
If anyone is finding this video (because CM is amazing and you should be finding them) and trying to do this with the new Input system. Go to your camera and add a Physics Raycaster OR Physics 2D raycaster to your camera first. Then the events they are showing you will work. (If not using UI, I believe you may need to add a collider to the object)
Hope this helps someone!
Thanks ! I almost gave up this tutorial in the 2 first minutes because it wouldn't show me the events
I am following in Unity 6, but no problems so far. I want to use the new Input System, for mouse input, how can I do that?
Thank you CodeMonkey as always! I made a slightly different variation that uses Triggers for the itemSlot to talk with the DragDrop class to tell it where to place the item if any part of the item enters the ItemSlot rather than just the mouse cursor.
It's really awesome seeing your way of doing it, and discovering another way of doing it to fit my specific desires!
Awesome! That's exactly what I hope people do with these tutorials, take them as a base and apply them to their specific use case, nice job!
The events explained by you are just fascinating, this guided me a lot and helped me make a custom inventory for my game!
Thank you for the tutorial. It's very concise and helpful.
A small tip: you don't need to add a canvas group to block raycasts for the dragged object, just grab its image component and set raycastTarget = false;
So simple and nice! After 10 hours spent for my experiments with drag and drop you show me how to do this with a few lines of code... Thank you!
in case any other UI noobs out there run into the same issue...
my console wasn't showing any click event debug messages-- the problem was i tried to make my own canvas by making an Empty and adding a Canvas component to it -- which is not the right way to go about it. : )
To solve this, go to the hierarchy and right click > UI > Canvas. This will generate a good Canvas with a graphic raycaster, and an Event System, both of which are needed for these scripts to work as shown!
Thanks so much. ;)
You can also add a solo Event System from right click > UI > Event System if yours is missing for some reason.
(When you copy paste a canvas from a different scene for example :))
You may also need to add a *Physics Raycaster* to your *main camera* game object, for anyone who it still isn't working for :)
Tip: by default unity has a threshold on drag, meaning the object starts following after the mouse has moved an amount in some direction.
To avoid this and have the object move exactly under where you click, you need to implement the *IInitializePotentialDragHandler* interface and inside *OnInitializePotentialDrag* set *eventData.useDragThreshold = false*
ty
I was going crazy trying to figure out why there is such a delay/lag when I drag even using the script exactly.
I added IInitializePotentialDragHandler
public class DragnDrop : MonoBehaviour, IPointerDownHandler, IBeginDragHandler, IEndDragHandler, IDragHandler, IInitializePotentialDragHandler
and
public void OnInitializePotentialDrag(PointerEventData eventData)
{
eventData.useDragThreshold = false;
}
But that didn't fix the problem sadly. Is this what you meant with your advice? Thanks!
Thank you so much! Came to the comments looking for this exact issue!
THAT'S WHAT I WAS LOOKING FOR, THANK YOUUUUU
It works for Mouse but there is still Drag threshold when using it for touch screen. any idea ... anyone , why ?
Thank you so much for making this video. I've been going crazy for an hour trying to get OnDrop events to trigger by messing with Override Sort Order, but what I really needed to do was add a CanvasGroup and blockRaycasts as per your video. THANK YOU!
This man, without a doubt, creates some of the best tutorials. His tutorials are easy to follow and are very useful. Stay blessed, Code.
I'm glad my videos have helped you! Thanks!
If you are using the new Unity Input Sytem this wont work by default. You need to go to Edit --> Project Settings --> Player --> Other Settings --> Change the setting "Active Input Handling" to both.
still doesn't work
One of the best Unity channels of RUclips...
Your videos are always on point, best topics 👌
Where ever i search about something, i find u immediately 😧, u are legendary man thank u a lot 🙏
I just wanted to say thank you so much for the video! This tutorial helped me along the way with my thesis work so I am especially grateful
I'm glad it helped! Thanks!
This is maybe the best tutorial I've ever come across. It feels like the guy is an actual expert, rather than just a hobbies who decided to try putting up a few videos. I learnt a tonne, including how to use the EventSystem properly. (I've been adding colliders that I don't really need.) Really good work.
Thanks! I'm glad you found it helpful!
See, THIS is useful and quick game dev I love. I learned more here about game dev then I did on the first few videos of a Udemy course lol. Thanks
YEeEeEeEeeeeEEEsS! OMG thank you so much this is exactly what I needed!
We all love you CodeMonkey, just know it :D
You have some of the best tutorials! Great job!
Man, I had troubles getting DragDrop to work properly especially when I get into the NRE, long before I found this tutorial and adapted it to my code and made it work just the way I wanted. Thanks, Code Monkey.
You got the best unity tutorials out there... fantastic content!
Thanks!
This helped me a lot. I've followed some guides and most of them just turn raycastTarget as false during dragging. It never worked for me, because I've added a text field to the image. If your objects also have other components, like a text field, you need to prevent the canvas group from blocking raycasts.
Hi Codemonkey I have a problem,
I have done everything exactly as in your video but my item goes too far over the mouse, even tho i have the: rectTransform.anchoredPosition += eventdata.delta / canvas.scaleFactor;
No errors and it works, but only this little bit doesnt(i also have debug.log done and it triggers the event)
thx for tutorial dude! This iş very useful!
Thank you so much! Your videos are always right on point!
Clean, simple and overall a perfect video! Appreciated a lot.
amazing tutorial as always
Awesome tutorial Code Monkey 🙇🏻♂👏
Thanks for it 🤝
I'm glad you liked it! Thanks!
Cool But :) 9:28 will work only if item & ItemSlot have Pivot set to Middle & Center?
The best Lesson! THank you. It is only necessary to clarify that the lesson refers to the UI
If you use a Physics Raycaster on your EventSystem you can use this same method on world objects
@@CodeMonkeyUnity i was trying drag and drop gameobjects in scene and this method not work. But thanks a lot. This lesson was very helpfull.
Another banger... Thanks Code Monkey!
Using those interfaces is really neat! Thanks a ton for this amazing tutorial 👏🏻 To implement a whole drag n drop inventory is a hell of a project but it so much worth it once it is up and running. 😎
Would it be possible to draggable object inside Scroll Rect? Please explain how to make it if it is possible?
for some reason the PointerEventData is not called when i test it on my Android phone. How do i fix this?
When I drop the item it takes the reference from the canvas not from the slot, what should I do? I'm using a panel to store the slots.
Not me getting a codemonkey ad while watching the video 😳
Hello I'm very new to unity and I'm trying to make a drag and drop system for a card game. I keep getting stuck when the "canvasGroup.blocksRaycasts = false;" doesn't work. The "blocksRaycasts" section is always marked as an error with the ID CS1061. I have no idea how to resolve this. Thank you!
I found this very helpful getting my own implementation working. Thank you!
May the gaming gods bless you. I was having issues with items not dragging at same speed, it was the scale factor.
Great tutorial!
Just a quick editor bug that I discovered. If the editor is not focused (i.e. you tabbed out and back in) the scale factor of the canvas is incorrect.
In my specific case, I have my editor set to play in Unfocused mode which caused this particular error. If you focus the editor by clicking anywhere, then drag the object, it will work.
(edit): As an aside, this video helped me setup my UI and its customization to exactly how I wanted. So quick and easy! Thank you again!!!
Thank you very much! Very helpful, also did not know about OnDrop haha.
By all means, this saved me life
I never realized these were built in events -_- I feel so dumb, I find myself brainstorming how to do things at work some days and create these huge complicated ways of accomplishing things that could of been done much simpler lol
Good work! Thanks :)
Thank you for the tutorial. This works fine if these UI objects are only children of the canvas. If they are children of anything within the canvas, their positions are offset; the more parents they have, the bigger the offset. Not sure how to fix the offset, but any suggestions would be great.
*Edit: found a solution, using a panel and having that as a child of a canvas works. I was using just an image as a panel as I didn't really see the use for the panel, but now I know.
So, your image and yout 'item' are both children of that panel? im trying that
PS: it worked!!
@@eduardoneis2691 nice!
Had the same issue, expected the anchor position to update - PosX and PosY are what get updated.
Replace
eventData.pointerDrag.GetComponent().anchoredPosition = this.GetComponent().anchoredPosition;
With
eventData.pointerDrag.transform.position = this.transform.position;
Then the anchor position and layers of objects doesn't seem to matter.
@@DrRoncin you just saved my life
@@DrRoncin Nice trick! Thanks.
Hello,
Please tell me How to swap items. Thanks
I wrote the exact same code and attached it to my sprite, but it's not working for some reason
He is using canvas ui elements not normal sprites.. therefore it was not working..
Great video this has really helped me with my drag and drop game. Thank You so much.
Solved: Can't get it to work for me. I have the exact same code setup as you do up to 4:50, but absolutely nothing is showing up in the console debug and the drag/drop function doesn't work at all. I've tried deleting the script component and creating it all again and using it on different assets, but still nothing. Any ideas?
You don't even see the OnPointerDown? Is the script attached to the object? Does you have an EventSystem in your scene? Does your Canvas have the default setup with the Graphics Raycaster?
@@CodeMonkeyUnity Okay, you got me in the right direction! I did not have an EventSystem added, and I needed to get a 2d Raycaster on my camera and a collider on my object. Then it started registering inputs and printing to the console. The movement scale is way off still (1 pixel on screen = about .5 units of transform), but it seems like there's some background stuff for me to learn with the scaler that will help address this. Thank you so much!
Thank you Code Monkey! :D
Excellent explanation! Thank you for sharing!! My snapping worked using GetComponent.position instead of GetComponent().anchoredPosition...
Is there any way to compare if the Obj is not on ItemSlot would be transformed to its initial position? For example, if I drop the draggable obj in another position in the scene that is not the ITemSlot, I want the draggable obj set to its initial position.
Can you make it so that you can rotate it too? With A and D
hey code monkey i have some question about this tutorial, it turns out my item is behind my slot item any suggestion of it?
Sorting order for UI elements is based on position in the hierarchy, drag that object to "lower" in the hierarchy to make it render after which will put it on top.
Through code you can use transform.SetAsLastSibling();
Thank you so much! look for that info all day
Super clear, and very easy to use. Thank you Master.
Thanks for the great overview. Instead of adding the CanvasGroup you can just use the Image component of the dragged item and write: "_image.raycastTarget = false;" (at least in Unity 2022, haven't tested older versions but it should work as well)
@3:53 When I have implemented the same code, the onDrag is only called once no matter how much I move the mouse. Any ideas?
👏🏾👏🏾👏🏾👏🏾👏🏾
Great great tutorial!
Fast and objective.
Thank you!!
I am trying to use this on my World Space Canvas. I build something like a click-adventure. I don't want to interact with my Inventory UI right now, I want to interact with the world, so the position of my interactable objects need to be constant). Sadly my mouse moves way faster (I assume ~1.5x faster ) than my Item, when dragging. I don't know why. "canvas.scaleFactor" seems to not have an effect on my World Space Canvas. Every Child and Parent Scale is 1. My World Space Canvas has a Scale of 0.01
I have no idea how to fix that, does anyone have an idea?
Same problem as mine. Can anyone help, please
i am also trying to do something similar but cant find a solution other than making them gameobjects
I have been trying today. I have a pan and zoom script that adjusts an orthographic camera on my World Space Canvas. I found out that the camera size has a major impact on how it moves. But I have not figured out how to use this to correct the movement.
Edit1: I thought I figured it out but when I exported the game and tested it as webgl, there still seems to be a secret scale factor.
@@joerideman I am not really up-to-date anymore on that topic, but maybe you should check the Canvas scale and also if any parent object have a different scale but 1.
You have to divide every parent of your parent. For example, if you have a item container as a parent of your item you have to do:
rectTransform.anchoredPosition += eventData.delta / canvas.scaleFactor / itemcontainer.transform.localScale;
Code Monkey That was a Great Tutorial, but i just wanna ask what is the type of data that stands in that "eventData.pointerDrag", like the name of the object or something?
It's a GameObject reference
Great tutorial !
Helpful as always, thanks!
Thank you man. You're best
i had so many problems using anchored position cause the canva scale reference resolution sometimes does not match the player screen resolution and then eventData delta returned a wrong delta.. i fixed it using transform.position instead of rectTransform.achoredPosition.
Man, you are the best
How to make Hello world appear in the center of screen after you dropped the item in the box? Help.
How do you use this on multiple item slots instead of just 1?
Is there a way to make it so that once the item has to be in a slot and cannot be anchored somewhere random in the scene? So if the item is not in a slot, then it goes back to the first slot
Try parenting and un parenting also explore setasfirst/ lastsibling
Nice and easy, great tutorial, thank you very much.
I find it quite outrageous, that such things are not available out-of-the-box. This would be the base functionality for creating virtual board games, like chess. Unity is a good engine but has the weirdest holes in its basic functionality.
I have a inventory system where each slot object has a background image and a child item image. When I drag the item image of a slot over others slot that are rendered before the source slot in the hierarchy the image just go behind the background image of those slots. Should I just make a seperate canvas for each item image or is there a better way to solve this
Does this work for game objects that are not children of Canvas, for example I want to drag and drop my player prefab
You can receive EventSystem events on regular Game Objects if they have a Collider and you add either the PhysicsRaycaster or the Physics2DRaycaster
Is there a code where the object is put back into its original position if you drag it into the wrong place?
If this isn't outdated, this will be _exactly_ what I need for what I'm doing right now.
...great, the object I want to move is an object without a Rect Transform component.
Nevermind, I fixed it by realizing that I didn't need an empty object to hold multiple objects and could instead use the background image as the parent to everything else, and move the scripts on the empty parent to the image.
That is Great.. but if i have two objects how and tried to drag it is becoming behind.. how to make the draged object always on top. thanks
I couldn´t do it. Debug.Log dosen´t work. There is any config for visual and unity work propetly?
If the script extends MonoBehaviour and is attached to a Game Object that is enabled then it has to work. So you probably just didn't add the script to a game object
thanks a ton, im trying to make a card game and I need to drag and drop and this works great
Very clean guide. The only thing it misses is ability to work with the new input system.
Thank you so much for this!
Months ago i wanted to implement this system, but i had problem with scrollable ui. Basically if you wanted to scroll, you had to drag ui vetrically and drag in others directions, when u wanted to drag object out. But this was much time consuming, so i implemented buy button instead. :D
I have a scrollable ui inside of which is the object I want players to be able to drag and yeah... It just doesn't seem to work. When I drag the object it jitters around the center of the screen and that's about it.
Very great tutorial. Btw what outro music is it in the end of the videos?
It's just one question that one of my friends asked. Here's mine:
Have you attended any course before/while/after jumping into game development related to it?
Not sure the exact name, its from the RUclips music library.
Most of what I know is from just learning in my own time, many years spent googling and building things, I did go to college for a year but never completed it.
@@CodeMonkeyUnity Thank you very much for your response. College is a good thing, but there are cases when it's just unnecessary.
Anyway, keep up the good work!
one small note: make sure to have the ray caster on canvas object
So amazingly helpful! Thank you.
How would I go about the item snapping back to it's original position if it isn't dropped in a slot?
Just store the original position and rotation of the object in variables.
And if the item is not dropped in a slot you can then just reset the current position and rotation to your stored variables.
Hello,
Thank you so much for this awesome tutorial. Everything is working great. Can you please tell me How to swap items? Thanks
Ohhhh really usefull thanks ! :)
As always with this guy, these videos work to a point and then I need to find someone better to show how to actually get it working. Guessing it's just out of date info. But it's a consistent issue
What exactly couldn't you get working? Nothing here is out of date
Err... Hello world ? Prefabs ? each prefab must have a canvas inside ?
i have two childs in one object and i want to place this both in grids at two place how to do this? like dicedom merge puzzle game
when press same time 2 button like ( right , left ) its making problem! help please.
I have to put items in the window containing items, but what should I do?
Long shot asking a question a year after publication, but...
So i replicated code @ 2:20, and the consol do not return any event,
i assumed it was because i was pushing it to a 3d object so i created a simple 2d sprite and consol still do no return a event.
only outlier i can think of, i do not have a "event System in my sampleScene, i am not sure what it is or how to add it to the project.
(i assume that the main reason why my code do not work)
UI events are only triggered on UI elements, it won't work on a MeshRenderer or SpriteRenderer.
So onpointerdown and ondrop event requires a raycast from mouseposition
I have a bit of a problem that when dragging and dropping the item "code itemslot" I don't get an object when dragged in. Help me please.
Everything works but whether or not OnDrop triggers is really inconsistent. Does the object utilizing OnDrop need to be under your mouse, or under the origin of the object being dropped?
i have problem that when my item is in slot it not moving again, what i miss even i check code again
For those who try this for your 3D Game: Pointer functions work only for UI Elements. If you want to use it on 3D Object you need to use "public void OnMouseDown()". Correct me If I'm wrong but this is the only solution that worked for me. :)
You can also use a Physics Raycaster instead of a Graphics Raycaster on the EventSystem. Doing that will make these functions trigger on world objects if they have Physics colliders.
Thank you ! You save my day !!!!
how I can make the object reset his position back to the original on EndofDrag?I can figure this out, I tried with:
public Vector3 startpos;
on Start:
startpos = transform.position;
and on EndofDrag
transform.position = startpos;....but not working
3:00 What do you pressing to complete the rest of the code? how to setup it?
Ctrl + . to get the quick actions, or click on the lightbulb on the left side
It's a standard Visual Studio feture