C# script to drag and drop GameObject using mouse cursor.
using System.Collections; using System.Collections.Generic; using UnityEngine; // ? 2017 TheFlyingKeyboard and released under MIT License // theflyingkeyboard.net public class DragAndDrop : MonoBehaviour { public float moveSpeed; public float offset = 0.05f; private bool following; // Use this for initialization void Start () { following = false; offset += 10; } // Update is called once per frame void Update () { if (Input.GetMouseButtonDown(0) && ((Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position).magnitude <= offset)) { if (following) { following = false; } else { following = true; } } if (following) { transform.position = Vector2.Lerp(transform.position, Camera.main.ScreenToWorldPoint(Input.mousePosition), moveSpeed); } } }
I can’t click my button when I use your script. Do you know why?
Hey Steve, could you give me a little more detail about what you are trying to do, and how exactly does it not work?
I think…You should adjust youre public movespeed.
when the movespeed is 0, object does not move.
So~check the movespeed.
Hi. Steve.
You should check the script [moveSpeed].
When the moveSpeed is ‘0’, the object does not move.
Trying to adjust moveSpeed ‘1’ 0r ‘2’.
Then, it will be working!
Hey, could you maybe help me with something?
For some reason the script doesn’t work. I’ve put a 2d box collider around the my object. But it won’t move when I try to click and drag it. Can you maybe help me with this?
Maybe you have too small offset or too big camera orthogonal size or maybe the colliders are blocking that object, could you send me a screenshot of your scene and object settings? I will try to help 🙂
Hi,
Thank You very much for Your work, it’s really helpfull.
Could You tell me what should I do to make possible moving 4 objects? I have 4 sprites and i would like to move separately each of them. Is this something much more complicated??
Thx
I’m not really sure what you are trying to achieve, but you can just add this script to 4 separate sprites. Maybe they are to close to each other.
Adjusting offset helped, I dont know why before with offset 0.01 nothing happened. It works fine. Thank You !!!
I’m glad to hear that 🙂
Thank You for this work is amazing!!!
I want to apply this drag and drop to a panel. it’s not working. Help me please …