Simple Drag Drop (Unity Tutorial for Beginners)

  Рет қаралды 320,956

Code Monkey

Code Monkey

4 жыл бұрын

✅ Get the Project files and Utilities at unitycodemonkey.com/video.php...
Let's make a very simple Drag and Drop in Unity, great for an Inventory System.
Simple Inventory System in Unity (Store, Use, Stack and Drop Items)
• Simple Inventory Syste...
If you have any questions post them in the comments and I'll do my best to answer them.
🔔 Subscribe for more Unity Tutorials / @codemonkeyunity
See you next time!
🤖 Join the Community Discord / discord
📦 Grab the game bundle at unitycodemonkey.com/gameBundl...
📝 Get the Code Monkey Utilities at unitycodemonkey.com/utils.php
#unitytutorial #unity3d #unity2d
--------------------------------------------------------------------
Hello and welcome, I am your Code Monkey and here you will learn everything about Game Development in Unity 2D using C#.
I've been developing games for several years with 7 published games on Steam and now I'm sharing my knowledge to help you on your own game development journey.
You can see my games at www.endlessloopstudios.com
--------------------------------------------------------------------
- Website: unitycodemonkey.com/
- Twitter: / unitycodemonkey
- Facebook: / unitycodemonkey

Пікірлер: 653
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
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
@lexmakes
@lexmakes 4 жыл бұрын
@CodeMonkey, hey! Thanks for this! Can you help? eventData.pointerDrag.GetComponent().anchoredPosition = GetComponent().anchoredPosition; dont work in Grid Layot Group. How fix it?
@courageafbet2607
@courageafbet2607 4 жыл бұрын
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.
@aurelienlerochbermuda6600
@aurelienlerochbermuda6600 4 жыл бұрын
@@lexmakes Try to use eventData.pointerDrag.GetComponent().position = GetComponent().position; work for me
@DjagoMorshosties
@DjagoMorshosties 4 жыл бұрын
better you use transform.position = Input.mousePosition; then you don't need to worry about canvas scaling etc.
@ryana.9821
@ryana.9821 4 жыл бұрын
@@DjagoMorshosties Thank you, saved some of my hair from being rippedout.
@TMosier88
@TMosier88 2 жыл бұрын
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!
@sparfild701
@sparfild701 2 жыл бұрын
Thanks ! I almost gave up this tutorial in the 2 first minutes because it wouldn't show me the events
@Shrarder0000
@Shrarder0000 3 жыл бұрын
The events explained by you are just fascinating, this guided me a lot and helped me make a custom inventory for my game!
@tjaartvanderwalt81
@tjaartvanderwalt81 3 жыл бұрын
This 10 minute video saved me probably three hours worth of effort, thank you very much.
@timurnurlygayanov3208
@timurnurlygayanov3208 3 жыл бұрын
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!
@robmattson
@robmattson 3 жыл бұрын
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!
@joshuadrewlow
@joshuadrewlow 3 жыл бұрын
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. 😎
@kpickett9128
@kpickett9128 Жыл бұрын
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!
@reivaxcorp
@reivaxcorp Жыл бұрын
Thanks so much. ;)
@lrizzard
@lrizzard 2 ай бұрын
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 :))
@Zyugo
@Zyugo 2 жыл бұрын
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.
@dio8440
@dio8440 4 жыл бұрын
Your videos are always on point, best topics 👌
@personalgamedevyt9830
@personalgamedevyt9830 9 ай бұрын
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!
@CodeMonkeyUnity
@CodeMonkeyUnity 9 ай бұрын
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!
@mboog12
@mboog12 Жыл бұрын
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;
@ksepastremenos
@ksepastremenos 3 жыл бұрын
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*
@peterferencz
@peterferencz 3 жыл бұрын
ty
@turnip4073
@turnip4073 2 жыл бұрын
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!
@QaziTV
@QaziTV 2 жыл бұрын
Thank you so much! Came to the comments looking for this exact issue!
@akstis4183
@akstis4183 2 жыл бұрын
THAT'S WHAT I WAS LOOKING FOR, THANK YOUUUUU
@anupammahajan7540
@anupammahajan7540 2 жыл бұрын
It works for Mouse but there is still Drag threshold when using it for touch screen. any idea ... anyone , why ?
@zezooalzezoo5200
@zezooalzezoo5200 2 жыл бұрын
Where ever i search about something, i find u immediately 😧, u are legendary man thank u a lot 🙏
@karficzfrizack2711
@karficzfrizack2711 4 жыл бұрын
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.
@markaj_
@markaj_ 4 жыл бұрын
still doesn't work
@martinds93
@martinds93 3 жыл бұрын
One of the best Unity channels of KZbin...
@kleinerobin4663
@kleinerobin4663 4 жыл бұрын
YEeEeEeEeeeeEEEsS! OMG thank you so much this is exactly what I needed!
@mertcanguven1326
@mertcanguven1326 Жыл бұрын
Clean, simple and overall a perfect video! Appreciated a lot.
@OPTactics
@OPTactics 2 жыл бұрын
You have some of the best tutorials! Great job!
@n0expressi0n16
@n0expressi0n16 4 жыл бұрын
amazing tutorial as always
@jean-michel.houbre
@jean-michel.houbre 3 жыл бұрын
Super clear, and very easy to use. Thank you Master.
@DannyBoy443
@DannyBoy443 Жыл бұрын
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
@EspiritoDoLugar
@EspiritoDoLugar 4 жыл бұрын
👏🏾👏🏾👏🏾👏🏾👏🏾 Great great tutorial! Fast and objective. Thank you!!
@manicmillennial3287
@manicmillennial3287 4 жыл бұрын
Thank you Code Monkey! :D
@fedhori4407
@fedhori4407 4 жыл бұрын
Thank you for your well-made videos. It always help me a lot.
@Brunoenribeiro
@Brunoenribeiro 3 жыл бұрын
You got the best unity tutorials out there... fantastic content!
@CodeMonkeyUnity
@CodeMonkeyUnity 3 жыл бұрын
Thanks!
@speedrob
@speedrob 4 жыл бұрын
As always good stuff... might mess around with this one and tailor it toward more dragging from the inventory and placing traps within a radius of the player and if it's not colliding with anything. Much better than my current way, click on the item (this case a mine) an it places at your current position. Very cool stuff thou man.
@theplaymakerno1
@theplaymakerno1 Ай бұрын
This man, without a doubt, creates some of the best tutorials. His tutorials are easy to follow and are very useful. Stay blessed, Code.
@CodeMonkeyUnity
@CodeMonkeyUnity Ай бұрын
I'm glad my videos have helped you! Thanks!
@user-sn8lw
@user-sn8lw 4 жыл бұрын
Thank you man. You're best
@mohammadalkhalailah7395
@mohammadalkhalailah7395 4 жыл бұрын
Great job as always , thanks.
@dankel317
@dankel317 3 жыл бұрын
this is how a good tutorial should be! thank you for making this so easy to understand! :)
@MateoAlbertoGarcia
@MateoAlbertoGarcia 4 ай бұрын
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
@CodeMonkeyUnity
@CodeMonkeyUnity 4 ай бұрын
I'm glad it helped! Thanks!
@nemanjakomar1422
@nemanjakomar1422 4 жыл бұрын
Thank you so much! You probably saved me days of work
@itaylorm
@itaylorm Жыл бұрын
I found this very helpful getting my own implementation working. Thank you!
@457Deniz457
@457Deniz457 4 жыл бұрын
Ohhhh really usefull thanks ! :)
@adhochero6619
@adhochero6619 2 жыл бұрын
thanks a ton, im trying to make a card game and I need to drag and drop and this works great
@aussieraver7182
@aussieraver7182 2 жыл бұрын
Helpful as always, thanks!
@1lsgaming27
@1lsgaming27 4 жыл бұрын
I might not need this now But I'll keep it for a future project. Thanks!
@darkdoom907
@darkdoom907 2 жыл бұрын
By all means, this saved me life
@Sermmy99
@Sermmy99 4 жыл бұрын
you are a lifesaver. Thank you
@user-sr1dn6vj2n
@user-sr1dn6vj2n Жыл бұрын
Great video this has really helped me with my drag and drop game. Thank You so much.
@jaicarey7023
@jaicarey7023 2 жыл бұрын
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!!!
@elliejayliquid
@elliejayliquid 3 жыл бұрын
Thanks, exactly what I was looking for! Didn't know there was an OnDrop event :)
@oldcat1790
@oldcat1790 4 жыл бұрын
Very clean guide. The only thing it misses is ability to work with the new input system.
@apothekerrie
@apothekerrie Жыл бұрын
So amazingly helpful! Thank you.
@EyalDeutscher
@EyalDeutscher 2 жыл бұрын
Thank you so much! look for that info all day
@coutnico-f9265
@coutnico-f9265 2 жыл бұрын
We all love you CodeMonkey, just know it :D
@FinitiXgameDepartment
@FinitiXgameDepartment 3 жыл бұрын
great!! thank you,you really helped me!
@gmangman123
@gmangman123 2 жыл бұрын
thx for tutorial dude! This iş very useful!
@JohnDoe-xi6df
@JohnDoe-xi6df 2 жыл бұрын
Good work! Thanks :)
@cwdgamedev822
@cwdgamedev822 Жыл бұрын
Another banger... Thanks Code Monkey!
@muhammadkhalilshafiq1465
@muhammadkhalilshafiq1465 4 жыл бұрын
Great! Helps a lot :)
@FlexFoundry
@FlexFoundry 3 жыл бұрын
Thank you very much! Very helpful, also did not know about OnDrop haha.
@UgurGulser
@UgurGulser 4 жыл бұрын
Thanks, very clear
@TheWorldsprayer
@TheWorldsprayer 3 ай бұрын
May the gaming gods bless you. I was having issues with items not dragging at same speed, it was the scale factor.
@animanecro8155
@animanecro8155 2 жыл бұрын
Thank you so much for this!
@ayoubchari242
@ayoubchari242 4 жыл бұрын
THANK you , you ask we when this video is helpful....! Is more than helpful...!!!
@joanagomes635
@joanagomes635 8 күн бұрын
Thank you so much! Your videos are always right on point!
@1501minhhuy
@1501minhhuy 2 жыл бұрын
Thank you ! You save my day !!!!
@isakgo7492
@isakgo7492 2 жыл бұрын
감사합니다 덕분에 유니티 개발이 재밌어졌어요
@RecOgMission
@RecOgMission 3 жыл бұрын
Hi again @Code Monkey. Another great tutorial with something I need! Thanks again. I have one problem, though. It seems when the item is in a hierarchy under the canvas that doesn't end up with a unit scale (the rectTransform, not the Canvas), the dragging happens to slow or fast. You have to divide by the "cumulative scale" of the rectTransform, but you can't use lossyScale, since I think it also takes into account the scale of the canvas and part of the hierarchy above it as well. It also doesn't work to use only lossyScale and ignore the canvas.scaleFactor. Any ideas?
@DrRoncin
@DrRoncin 3 жыл бұрын
Excellent tutorial.
@user-by3zr4oz1s
@user-by3zr4oz1s 2 жыл бұрын
Super Thank you!!
@phambaoha170
@phambaoha170 4 жыл бұрын
thank you man!
@suryaelz
@suryaelz 2 жыл бұрын
Very cool, thank you!
@ee.4021
@ee.4021 2 жыл бұрын
Thank you very much for the tutorial
@sooanlu27
@sooanlu27 3 жыл бұрын
You save my day
@y4ni608
@y4ni608 2 жыл бұрын
Great tutorial !
@gamedevbaiyi936
@gamedevbaiyi936 2 жыл бұрын
Thank you!!!
@MarkFilliph
@MarkFilliph 2 жыл бұрын
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.
@vedantsawant8527
@vedantsawant8527 4 жыл бұрын
Amazing video!! Everything worked out well !! Can you please tell how can I make multiple objects to fill in multiple slots. When I tried it, it didn't work !! Is there any way to do this multiple times in a scene ?
@ShaneP427
@ShaneP427 4 жыл бұрын
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.
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
Thanks! I'm glad you found it helpful!
@michaelsong741
@michaelsong741 4 жыл бұрын
Hey Code Monkey, I really like the way you structure your videos - you take subject matters of all kinds even some really complex ideas and break them down into practical procedures that anyone can follow. I mean that in the best way possible and I wish more people would make tutorials like the way you make them. Having said that, I hope you don't mind me dropping a request on a subject matter. With ECS coming up, I've been slowly pushing myself towards higher-performance code. But one of the things I think ECS does not fix is - animation/material rendering overhead when you use mechanim/skinned mesh renderers. Even without any code attached to some of my models, I can only have a couple hundred at most before my frames start massively dropping away. Do you think you can explore some of this and share some methods to optimize animation/material rendering? I've dug through lots of videos/blogs, while most of them do what they promise to do - they each work only under a very specific set of conditions. They become incompatible if you use shader graphs, multiple materials on a model, incohesive with mechanim (blended animations, multiple layers, state trees) - and so on so forth. If you have any ideas about this, I would really love to know - thanks in advance!
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
The new DOTS Third Person Shooter should be coming out at the same time as 2019.3 and I believe it contains a fully DOTS based animation system. So looking at how they did that will probably help. There's also the first DOTS demo they showed, the thousands of minions fighting on a bridge, I believe they were using skinned meshes and the project is available somewhere but can't remember where.
@danilocazaroto7545
@danilocazaroto7545 Жыл бұрын
Awesome tutorial Code Monkey 🙇🏻‍♂👏 Thanks for it 🤝
@CodeMonkeyUnity
@CodeMonkeyUnity Жыл бұрын
I'm glad you liked it! Thanks!
@illusionsofthegrave1274
@illusionsofthegrave1274 2 жыл бұрын
Thanks for outlining the basics! This is super helpful. I'm trying to add onto this stating "If image 1 is dropped onto image 2, show image 3. Else, show message" but it seems to be a little out of my technical expertise. Any tips help!
@balilobaludo7715
@balilobaludo7715 4 жыл бұрын
Amazing tutorial, exactly what I needed for my project, I'm just having problems with layers, the slot is ending up on top of the item
@CodeMonkeyUnity
@CodeMonkeyUnity 4 жыл бұрын
Sorting order in the UI is all about hierarchy position, make sure the UI is on a lower hierarchy position or a child of the slot. You can also use transform.SetAsLastSibling();
@yudoball
@yudoball 3 жыл бұрын
thanks it works!
@harryle1989
@harryle1989 3 жыл бұрын
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.
@averageenjoyer301
@averageenjoyer301 3 жыл бұрын
Hey very cool video!! Is their a way to restrict the drag and drop to one axis, so that you can move the item along the x but not the y axis for example?
@litalu2
@litalu2 2 жыл бұрын
tnx!!🥰
@MwdCraft
@MwdCraft 3 жыл бұрын
thanx so much
@katjalua
@katjalua 3 жыл бұрын
Hi! Great tutorial! How can I make sure that the right object can only be dropped into the right box when I have multiple objects and boxes? It should be possible to change the correct box for each item in the inspector.
@MatusFinchus
@MatusFinchus 4 жыл бұрын
Thanks for this - superb, simple and effective. :) I'm working on a card-based turn-based game (think Slay The Spire mixed with Darkest Dungeon) and this is a key part of the UI.
@sebastianmora4050
@sebastianmora4050 2 жыл бұрын
Thanks :)
@RTWrename
@RTWrename 3 жыл бұрын
ok then so now, how can I use this to instanciate an object in the map? and to store it in back to inventory? for example with the mouse
@AtomHMusic
@AtomHMusic 4 жыл бұрын
Thanks!
@maltedwheaties3339
@maltedwheaties3339 4 жыл бұрын
How do you adjust this for a two-block wide draggable object? I am using this for a 2D platformer where you drag blocks (sprites with colliders) using a world-space canvas. I have item slots in a 10x10 grid, and have the 1x1 draggable objects (the potion in this tutorial) working well. How would you modify the code to allow for different shape blocks? Thanks
@glebkrel5526
@glebkrel5526 3 жыл бұрын
Крутое видео)))) вот то что мне и было нужно))) спс
@ahadnazari9110
@ahadnazari9110 3 жыл бұрын
very good 🙏🙏🙏
@Prod.ByMoonlight
@Prod.ByMoonlight 2 жыл бұрын
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)
@ozguroz5340
@ozguroz5340 3 жыл бұрын
Thanx alot..
@danielberec4130
@danielberec4130 3 жыл бұрын
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
@SharathThe1
@SharathThe1 Жыл бұрын
Try parenting and un parenting also explore setasfirst/ lastsibling
@andrejusvoisnis8087
@andrejusvoisnis8087 3 жыл бұрын
Very nice
@danielvilla5070
@danielvilla5070 4 жыл бұрын
Hi, great tutorial, is it possible to this vuforia for augmented reality app ? Thank you in advance
@BitbeastGames
@BitbeastGames 4 ай бұрын
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)
@smabn5
@smabn5 2 жыл бұрын
Thnaks
@Future_Guy
@Future_Guy 2 жыл бұрын
Any way to implement this when the pointer is not over the drop object but the item you are dragging is? Like any part of the dragged item is over the drop zone (but the pointer itself is not) ... I feel like some hover function would work here or perhaps a bounds check?
@mrx10001
@mrx10001 4 жыл бұрын
Incase it drags very slightly and doesn't work, even after adding the canvas scaler thing. Try disabling the new input system, ie use the old one with the old input event system, on the event's gameObject. For some reason it doesn't want to register the pointer delta's value correctly, even if you set it correctly in the new UI event system. and I've so far tested it on numerous 2019 versions.
@Cyneprepou
@Cyneprepou Жыл бұрын
The best Lesson! THank you. It is only necessary to clarify that the lesson refers to the UI
@CodeMonkeyUnity
@CodeMonkeyUnity Жыл бұрын
If you use a Physics Raycaster on your EventSystem you can use this same method on world objects
@Cyneprepou
@Cyneprepou Жыл бұрын
@@CodeMonkeyUnity i was trying drag and drop gameobjects in scene and this method not work. But thanks a lot. This lesson was very helpfull.
@tohedul111
@tohedul111 3 жыл бұрын
Hi, I want to add and drag and drop object only between the tilemap's tile. Can you suggest to me how can I achieve that with an example?
Drag and drop in Unity UI - create your own inventory UI!
12:47
Coco Code
Рет қаралды 100 М.
How to Craft Items with Scriptable Objects! (Unity Tutorial)
19:46
БИМ БАМ БУМ💥
00:14
⚡️КАН АНДРЕЙ⚡️
Рет қаралды 4,7 МЛН
НРАВИТСЯ ЭТОТ ФОРМАТ??
00:37
МЯТНАЯ ФАНТА
Рет қаралды 8 МЛН
Каха заблудился в горах
00:57
К-Media
Рет қаралды 9 МЛН
Oh, wait, actually the best Wordle opener is not “crane”…
10:53
Unity INVENTORY: A Definitive Tutorial
35:21
Coco Code
Рет қаралды 108 М.
Ability Bar in Unity (Swap Weapons/Items)
29:07
Code Monkey
Рет қаралды 32 М.
I Made the Same Game in 8 Engines
12:34
Emeral
Рет қаралды 4 МЛН
Как реализовать Drag and Drop в Unity UI?
16:32
Лавка Разработчика
Рет қаралды 15 М.
Unity3D - Scriptable Object Inventory System | Part 1
31:31
Coding With Unity
Рет қаралды 325 М.
How to Make a Good 2D Camera
11:38
Game Maker's Toolkit
Рет қаралды 394 М.
Can AI code Flappy Bird? Watch ChatGPT try
7:26
candlesan
Рет қаралды 9 МЛН