Unity Drag and Drop Script | (Unity 3D tutorial)
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
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?
Hi, I just got your script, it's great, but how can you get the whole project?
@@PlanshetkaCom Unfortunately I can't release the entire project because I don't own the license to everything in it
Snapping objects sounds like a good video, i'm looking forward to seeing it from you
Yes waiting for that
Yes I'm interested. Thanks, friend
You got everything to grow into a large dev channel, chapters, calm voice, sweet music, sub 15 minutes videos. I subbed !
Thanks for the encouragement!
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.
Finally! I've been looking for this for two days now, I was not able to make this work thanks!
Glad I could help!
I was searching for this for a long.....thanks a lot man
Looking forward to learn more from this channel
Glad to hear it and thanks for the support! I've got some fun stuff I'm working on RN
@@AIAdev really can't wait for it...
@@vaibhavjaiswal799 bro give me the assets
I just subscribed!!! Excellent presentation, well done!
Thank you for your subscription and kind words :)
Such a good video, thank u for this!
Helped me a lot, thanks ❤
Woow after two hours of looking I just found what I'm looking for. Many thanks!
Glad I could help!
Great tutorial, very easy to follow, even an idiot like me can (probably) do this correctly now. Pretty cool!
You've definitely got it! If you get hung up anywhere feel free to come back and ask any questions
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!
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.
Helped a lot thanks!
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!
Awesome tutorial man :)
Thanks!
This video helped and I am commenting down below as a result.
Saved my life dude :)
Imma need this for my game, thanks!!
no problem :) good luck on your game!
I yelled at my screen when you copy pasted code. Then I felt satisfied when you told the audience to refactor it!
lol
Thanks a lot for this tutorial!
You're very welcome!
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?
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 :)
@@AIAdev Hi!
How were you able to overlay a picture on a piece?)
Just commenting, to help that youtube algorithm :)
Many thanks
A quick question. What is the difference between this method and using a normal raycast that unity already provides?
Hi! How did you make such puzzle pieces?) How were you able to apply texture to them? Please answer)
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.
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 :)
You can certainly do that. I thought making a CastRay function just kind of made it a little more clear what was going on :)
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.
Certainly possible. I recommend using a Debug.DrawLine or Debug.DrawRay to visualize where your rays. That should make it easier to debug.
Great video!
Thanks so much!
@@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!!
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?
this should be fine as along as a mesh collider is attached. My pieces were modeled in blender
Great vidéo ! Thank you for this tutorial. How can i snap my objects on a board now ??
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.
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
@@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?
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.
Yep! You could instantiate a new version of the clicked gameobject.
Hi, I just got your script, it's great, but how can you get the whole project?
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
Awesome
Thanks :)
Stoppppp itttttt. This is hot fire FUUUULLLLAAAMMMEEESSS!!!
lol ty
Can you share your visual code setting....how you make it work exactly like visual studio....and work perfectly with unity....?
I actually use visual studio :)
@@AIAdev okay, I thought you said visual code in video so i just ask
@@vaibhavjaiswal799 I think I did :|. That's on me
This is the functionality I want in godot script.
How about drag and drop object like box in 3d space?
This tutorial still applies in that case too! Just different objects.
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();
Why does my object only move in the horizontal and not the vertical when I pick it up and move it?
I'd have to see your code to see why
is there a fix for this?
Where did you get the puzzle assets?
I made them :)
raycast is always hitting null for me its not working :(
I changed Cast Ray like this and worked:
private RaycastHit CastRay()
{
RaycastHit hit;
Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit);
return hit;
}
Snapping video please
Good
Cheers!
hello, does this still work on a new system?
Eh di
Really helpful tutorial for me absolute beginner, but why is my object shaking like crazy??😂
Its because of gravity
Sweet!♡ Like. A. Fine. Wine.🍷 it's too much for one image😍.. Just too much
😋
Doesnt work for me
does it work for mobile game?
The general concept should
@@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.
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;
}
}
[...]
@@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);
}
}
Nice tutorial please can i have the 3d models you use in this tutorial
Unfortunately they were lost due to a corrupted hard drive
for anyone new, this doesn't work anymore
If you join the discord i can help you.
NullReferenceException: Object reference not set to an instance of an object Why i have everithing like u
Make sure everything that needs to be assigned in the inspector has a value.
@@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?
If you click on the error it should take you to the section of code where the error is occuring
@@AIAdev i send u a screen shoot over discord
@@mauznemo cool. I'll respond there
Incredibox would like this
You get it because you need to drag and drop in the game
implementation and not work stop name it tutorial. wasting 12 mnt time
I'd love to help you if you let me know what doesn't work. Are you getting error codes?