Unity Drag and Drop Script | (Unity 3D tutorial)

Sdílet
Vložit
  • čas přidán 13. 06. 2024
  • In this session, we'll walk through how to create a c# script that will allow us to drag and drop 3d objects in Unity. To illustrate our script, we'll assemble a small puzzle. Before you leave, hit those like and subscribe buttons, it helps the channel a lot and it's absolutely free. And as always, the link to the source code is available in the description.
    ► Socials
    Twitter: / the_real_aia
    Discord: / discord
    My free web games: aiadev.fun/
    ► Get the script: unicornone.gumroad.com/l/drag...
    ► Detailed info on Raycasting from camera: • Unity Mobile Dev From ...
    ► Download Unity 3D: on.unity.com/3cbxhXY
    For more educational content on video game development, unity tutorials, and c# programming don't forget to subscribe!
    Chapters:
    0:00 Introduction
    0:27 Overview
    0:50 Setup
    2:15 Creating a unity drag and drop script
    5:21 Picking up and moving a 3d object
    9:23 Dropping a Unity3d object during run time
    10:50 Rotating a Unity3d object during run time
    12:08 Outro
    ········································­­·······································­·­····
    ****
    Get a 90% discount on a .fun domain for one year on www.get.fun using the coupon “AIA”
    ****

    #unity3d #unitytutorial #gamedev

Komentáře • 118

  • @AIAdev
    @AIAdev  Před 2 lety +53

    I had a lot of fun creating this little puzzle game. I implemented a snap and lock for when puzzle pieces are placed and oriented in the correct spot. Are you interested in seeing a tutorial on that?

    • @PlanshetkaCom
      @PlanshetkaCom Před 2 lety

      Hi, I just got your script, it's great, but how can you get the whole project?

    • @AIAdev
      @AIAdev  Před 2 lety

      @@PlanshetkaCom Unfortunately I can't release the entire project because I don't own the license to everything in it

    • @truongsonnguyen7056
      @truongsonnguyen7056 Před 2 lety +7

      Snapping objects sounds like a good video, i'm looking forward to seeing it from you

    • @sivacse24
      @sivacse24 Před 2 lety +2

      Yes waiting for that

    • @ericcastro007
      @ericcastro007 Před 2 lety

      Yes I'm interested. Thanks, friend

  • @minia3769
    @minia3769 Před 2 lety +9

    You got everything to grow into a large dev channel, chapters, calm voice, sweet music, sub 15 minutes videos. I subbed !

    • @AIAdev
      @AIAdev  Před 2 lety

      Thanks for the encouragement!

  • @martybonus728
    @martybonus728 Před rokem

    This was great! I watched a number of tutorials doing similar things, but this was the best of them. In particular, this implementation allows easier drag/drop movement along the z-axis. And if anyone is struggling with the object shaking, just tick 'is kinematic' on your rigidbody, if you're using one.

  • @Spartan195X
    @Spartan195X Před 2 lety

    Finally! I've been looking for this for two days now, I was not able to make this work thanks!

    • @AIAdev
      @AIAdev  Před 2 lety

      Glad I could help!

  • @vaibhavjaiswal799
    @vaibhavjaiswal799 Před 2 lety +1

    I was searching for this for a long.....thanks a lot man
    Looking forward to learn more from this channel

    • @AIAdev
      @AIAdev  Před 2 lety +1

      Glad to hear it and thanks for the support! I've got some fun stuff I'm working on RN

    • @vaibhavjaiswal799
      @vaibhavjaiswal799 Před 2 lety

      @@AIAdev really can't wait for it...

    • @hhcdghjjgsdrt235
      @hhcdghjjgsdrt235 Před 2 lety

      @@vaibhavjaiswal799 bro give me the assets

  • @remali26
    @remali26 Před 2 lety +1

    I just subscribed!!! Excellent presentation, well done!

    • @AIAdev
      @AIAdev  Před 2 lety

      Thank you for your subscription and kind words :)

  • @TheNando5005
    @TheNando5005 Před 2 lety

    Such a good video, thank u for this!

  • @rox.3346
    @rox.3346 Před 11 měsíci

    Helped me a lot, thanks ❤

  • @jaxowaraxa
    @jaxowaraxa Před 10 měsíci

    Woow after two hours of looking I just found what I'm looking for. Many thanks!

    • @AIAdev
      @AIAdev  Před 10 měsíci +1

      Glad I could help!

  • @punkrockprincess
    @punkrockprincess Před 2 lety +1

    Great tutorial, very easy to follow, even an idiot like me can (probably) do this correctly now. Pretty cool!

    • @AIAdev
      @AIAdev  Před 2 lety

      You've definitely got it! If you get hung up anywhere feel free to come back and ask any questions

  • @bigads2946
    @bigads2946 Před 2 lety +1

    Hey, great video. I've been trying to wrap my head around how you would implement a snap and lock and was woundering if you had any pointers? Keep up the good work!

    • @AIAdev
      @AIAdev  Před 2 lety +3

      for this particular example... the puzzle is already assembled. On awake all of the positions and rotations of the pieces are saved. Then all of the pieces get scrambled. When the player attempts to drop a piece it will only drop if it's the correct rotation and within a certain range of it's actual position.

  • @furkix2902
    @furkix2902 Před 2 lety

    Helped a lot thanks!

  • @benl2390
    @benl2390 Před rokem

    This is a great tutorial, thanks! I have two issues I've spent hours trying to fix, maybe you have advice. The first is that it only seems to work for me if the camera is top-down on the y world axis, then the grabbed object will move on the x and z axis, but if the camera is in a sort of first-person view, near 0 on the y world axis, the object will not translate on the z axis at all, only the x and y axis. In fact sometimes it pushes straight through the terrain collider to stay on the y axis, instead of moving on the z.
    The second issue I don't understand is that the object jitters +/- 0.5 world unit as I grab it, even when I let go of the mouse. Any advice? Thanks!

  • @vanshrana9508
    @vanshrana9508 Před rokem

    Awesome tutorial man :)

  • @gamedev1905
    @gamedev1905 Před rokem

    This video helped and I am commenting down below as a result.

  • @alinazario3648
    @alinazario3648 Před 7 měsíci

    Saved my life dude :)

  • @mikethebozo08
    @mikethebozo08 Před 2 lety

    Imma need this for my game, thanks!!

    • @AIAdev
      @AIAdev  Před 2 lety

      no problem :) good luck on your game!

  • @ChrisKarpyszyn
    @ChrisKarpyszyn Před 2 lety

    I yelled at my screen when you copy pasted code. Then I felt satisfied when you told the audience to refactor it!

  • @swalscha
    @swalscha Před 2 lety

    Thanks a lot for this tutorial!

    • @AIAdev
      @AIAdev  Před 2 lety

      You're very welcome!

  • @wormholeinteractive
    @wormholeinteractive Před 2 lety +3

    Hi there! Love the tutorial, and would love to see a tutorial on how you made these pieces in Blender? Was this a create-flat-then-extrude process?

    • @AIAdev
      @AIAdev  Před 2 lety +1

      yep! I got an image online of a 9 piece jigsaw puzzle, traced all the pieces, extruded them, then used bevel on the edges to round them out a little, then added some sub surface smoothing :)

    • @Dumkras_old
      @Dumkras_old Před rokem

      @@AIAdev Hi!
      How were you able to overlay a picture on a piece?)

  • @milanbordas3840
    @milanbordas3840 Před 2 lety +3

    Just commenting, to help that youtube algorithm :)

  • @marceljanz9905
    @marceljanz9905 Před 4 měsíci

    A quick question. What is the difference between this method and using a normal raycast that unity already provides?

  • @Dumkras_old
    @Dumkras_old Před rokem

    Hi! How did you make such puzzle pieces?) How were you able to apply texture to them? Please answer)

  • @GiveMeMilkPls
    @GiveMeMilkPls Před 3 měsíci

    thanks for the tutorial, and it's a bit late but will you make a tutorial on the snap and lock script or release it for access? thanks again.

  • @6xghr
    @6xghr Před 2 lety +2

    Thx for the tutorial!
    Maybe I'm wrong, but I think you don't need the CastRay() function by simply calling "if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo)) { do something }". It worked for me :)

    • @AIAdev
      @AIAdev  Před 2 lety +1

      You can certainly do that. I thought making a CastRay function just kind of made it a little more clear what was going on :)

  • @splican
    @splican Před 2 lety

    Hey! Love the video, perfectly explained! Is it possible to just turn the axis so that i can move my objects like on a wall? I tried to change the Vector3's but it won't work.

    • @AIAdev
      @AIAdev  Před 2 lety +1

      Certainly possible. I recommend using a Debug.DrawLine or Debug.DrawRay to visualize where your rays. That should make it easier to debug.

  • @ewwitsantonio
    @ewwitsantonio Před 2 lety

    Great video!

    • @AIAdev
      @AIAdev  Před 2 lety

      Thanks so much!

    • @ewwitsantonio
      @ewwitsantonio Před 2 lety +1

      @@AIAdev No prob! The quality community Unity videos have been drying up the past couple years, so it's nice to see some good content being created!!

  • @mikeyrichards5480
    @mikeyrichards5480 Před rokem +2

    This is an amazing tutorial and it really helped. However, for me, it doesn’t work with objects i imported from blender. Do you know how to fix this?

    • @AIAdev
      @AIAdev  Před rokem +1

      this should be fine as along as a mesh collider is attached. My pieces were modeled in blender

  • @tibd688
    @tibd688 Před rokem

    Great vidéo ! Thank you for this tutorial. How can i snap my objects on a board now ??

  • @SpaceMango
    @SpaceMango Před 2 lety

    Thank you so much for this video! I am working on a very small game where you organize your desk and it works great. I have an idea though but not sure how i'm gonna accomplish that so i'm asking the question here. I want to be able to cycle through different models when i have picked it up. For example; i have picked up a flower pot, but i don't want it to be a cactus in the pot, i want a red flower, so i press space to cycle between different flowers. My first thought is that i should make the other meshes as children to the flowerpot and then cycle through visibility.

    • @AIAdev
      @AIAdev  Před 2 lety

      That seems like a great approach if there’s only a handful of plants. If theres hundreds you might want to think about how to to dynamically load them

    • @SpaceMango
      @SpaceMango Před 2 lety

      @@AIAdev i was thinking about Maybe cycling between 3 or 4 different styles. Is it possible to put it in the same script or should i make a separate one for that?

  • @TheLespauljunior
    @TheLespauljunior Před 2 lety

    Is there a way to pick and move only a copy of the selected game object? I am looking to create an interface that can allow the user to select from a variety of different options, and I want the set of options to remain fixed.

    • @AIAdev
      @AIAdev  Před 2 lety +1

      Yep! You could instantiate a new version of the clicked gameobject.

  • @PlanshetkaCom
    @PlanshetkaCom Před 2 lety +1

    Hi, I just got your script, it's great, but how can you get the whole project?

    • @AIAdev
      @AIAdev  Před 2 lety

      I think I responded to this, but I unfortunately don’t have the rights to everything in the project to be able to release it

  • @gameobject5487
    @gameobject5487 Před 2 lety

    Awesome

  • @walterrape5381
    @walterrape5381 Před 2 lety

    Stoppppp itttttt. This is hot fire FUUUULLLLAAAMMMEEESSS!!!

  • @vaibhavjaiswal799
    @vaibhavjaiswal799 Před 2 lety +1

    Can you share your visual code setting....how you make it work exactly like visual studio....and work perfectly with unity....?

    • @AIAdev
      @AIAdev  Před 2 lety +1

      I actually use visual studio :)

    • @vaibhavjaiswal799
      @vaibhavjaiswal799 Před 2 lety +1

      @@AIAdev okay, I thought you said visual code in video so i just ask

    • @AIAdev
      @AIAdev  Před 2 lety +1

      @@vaibhavjaiswal799 I think I did :|. That's on me

  • @pequadcob2009
    @pequadcob2009 Před rokem

    This is the functionality I want in godot script.

  • @danegamedev
    @danegamedev Před 2 lety

    How about drag and drop object like box in 3d space?

    • @AIAdev
      @AIAdev  Před 2 lety

      This tutorial still applies in that case too! Just different objects.

  • @VaupellGaming
    @VaupellGaming Před rokem

    nice video, for new input system this works fine aswell, just instead of input handling (old system) it's now event system.
    ie:
    Using UnityEngine.Eventsystems;
    Public class whatevername : Monobehavior, IPointerDownHandler,
    public void OnPointerDown(PointerEventData eventData)
    {
    // Do mouse down stuff here, also only reacts to raycasts towards gameobjects that either has this script or parent has this.
    }
    Ohh,, almost forget, don't run mouse check in update anymore, it's called from the event system..
    Mouse pos you can just call from anywhere now, like this..
    Vector3 position = Mouse.current.position.ReadValue();

  • @soheilaboscarino8648
    @soheilaboscarino8648 Před 2 lety

    Why does my object only move in the horizontal and not the vertical when I pick it up and move it?

    • @AIAdev
      @AIAdev  Před 2 lety

      I'd have to see your code to see why

    • @lizzygomuroxz
      @lizzygomuroxz Před rokem

      is there a fix for this?

  • @LostSol25
    @LostSol25 Před 3 měsíci

    Where did you get the puzzle assets?

    • @AIAdev
      @AIAdev  Před 3 měsíci

      I made them :)

  • @AnecProductions
    @AnecProductions Před rokem

    raycast is always hitting null for me its not working :(

    • @JHJhonib10
      @JHJhonib10 Před rokem

      I changed Cast Ray like this and worked:
      private RaycastHit CastRay()
      {
      RaycastHit hit;
      Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit);
      return hit;
      }

  • @letthatbe
    @letthatbe Před rokem

    Snapping video please

  • @thg1nrediar
    @thg1nrediar Před 2 lety

    Good

  • @hayewolf356
    @hayewolf356 Před rokem

    hello, does this still work on a new system?

  • @z1d2g3c4
    @z1d2g3c4 Před rokem +1

    Really helpful tutorial for me absolute beginner, but why is my object shaking like crazy??😂

    • @z1d2g3c4
      @z1d2g3c4 Před rokem

      Its because of gravity

  • @hannahlewis6275
    @hannahlewis6275 Před 2 lety

    Sweet!♡ Like. A. Fine. Wine.🍷 it's too much for one image😍.. Just too much

  • @nerokuma
    @nerokuma Před rokem

    Doesnt work for me

  • @coffeebean7502
    @coffeebean7502 Před 2 lety

    does it work for mobile game?

    • @AIAdev
      @AIAdev  Před 2 lety +1

      The general concept should

    • @retzerbil867
      @retzerbil867 Před 2 lety

      @@AIAdev It still looks for when the user presses again, so the drag and drop doesn't really work. If you pick up a piece and release your finger it will then teleport to the new piece you press. Trying to figure this out right now, so that it works for mobile.

    • @retzerbil867
      @retzerbil867 Před 2 lety +2

      Update: I fixed it, what I did was to replace the Input.getMouseButtonDown(0) at the start of update with Input.touchCount == 1, and then under that do a new if statement with Input.GetTouch(0).phase == TouchPhase.Began. Then further down turn the else into an if with Input.GetTouch(0).phase == TouchPhase.Ended.
      That slightly changed the functionality from pressing and pressing again to drop, to touching and dragging and letting go to drop.
      Basically, it should look like this:
      private void Update()
      {
      if (Input.touchCount == 1)
      {
      if (Input.GetTouch(0).phase == TouchPhase.Began) {
      if (selectedObject == null)
      {
      RaycastHit hit = CastRay();
      if (hit.collider != null)
      {
      if (!hit.collider.CompareTag("drag"))
      {
      return;
      }
      selectedObject = hit.collider.gameObject;
      }
      }
      }
      if(Input.GetTouch(0).phase == TouchPhase.Ended)
      {
      Vector3 position = new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.WorldToScreenPoint(selectedObject.transform.position).z);
      Vector3 worldPosition = Camera.main.ScreenToWorldPoint(position);
      selectedObject.transform.position = new Vector3(worldPosition.x, 0f, worldPosition.z);
      selectedObject = null;
      }
      }
      [...]

    • @letthatbe
      @letthatbe Před rokem

      @@retzerbil867 or you can simply write Input.GetMouseButtonUp(0) as a new if statement ?
      void Update()
      {
      if(Input.GetMouseButtonDown(0))
      {
      if(_selectedObject == null)
      {
      RaycastHit hit = CastRay();
      if(hit.collider != null)
      {
      if (!hit.collider.CompareTag("Drag"))
      return;
      _selectedObject = hit.collider.gameObject;
      Cursor.visible = false;
      }
      }

      }
      if (Input.GetMouseButtonUp(0))
      {
      Vector3 position = new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.WorldToScreenPoint(_selectedObject.transform.position).z); //bunu alip world position'a esitliyoruz asagida
      Vector3 worldPosition = Camera.main.ScreenToWorldPoint(position);
      _selectedObject.transform.position = new Vector3(worldPosition.x, 0f, worldPosition.z);
      _selectedObject = null;
      Cursor.visible = true;
      }
      if (_selectedObject != null)
      {
      Vector3 position = new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.WorldToScreenPoint(_selectedObject.transform.position).z); //bunu alip world position'a esitliyoruz asagida
      Vector3 worldPosition = Camera.main.ScreenToWorldPoint(position);
      _selectedObject.transform.position = new Vector3(worldPosition.x, .25f, worldPosition.z);
      }
      }

  • @younesbelhit781
    @younesbelhit781 Před 2 lety

    Nice tutorial please can i have the 3d models you use in this tutorial

    • @AIAdev
      @AIAdev  Před 2 lety

      Unfortunately they were lost due to a corrupted hard drive

  • @AnecProductions
    @AnecProductions Před rokem +1

    for anyone new, this doesn't work anymore

    • @AIAdev
      @AIAdev  Před rokem

      If you join the discord i can help you.

  • @mauznemo
    @mauznemo Před 2 lety

    NullReferenceException: Object reference not set to an instance of an object Why i have everithing like u

    • @AIAdev
      @AIAdev  Před 2 lety +1

      Make sure everything that needs to be assigned in the inspector has a value.

    • @mauznemo
      @mauznemo Před 2 lety

      @@AIAdev I have an collider (box) on the object i want to drag, have the tag on it, the script is on the player. did i miss anything?

    • @AIAdev
      @AIAdev  Před 2 lety

      If you click on the error it should take you to the section of code where the error is occuring

    • @mauznemo
      @mauznemo Před 2 lety

      @@AIAdev i send u a screen shoot over discord

    • @AIAdev
      @AIAdev  Před 2 lety

      @@mauznemo cool. I'll respond there

  • @anandrishabh2672
    @anandrishabh2672 Před rokem

    Incredibox would like this

    • @anandrishabh2672
      @anandrishabh2672 Před rokem

      You get it because you need to drag and drop in the game

  • @earpgth8469
    @earpgth8469 Před 2 lety

    implementation and not work stop name it tutorial. wasting 12 mnt time

    • @AIAdev
      @AIAdev  Před 2 lety

      I'd love to help you if you let me know what doesn't work. Are you getting error codes?