C# script to drag and drop GameObject using mouse cursor.

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

// © 2017 TheFlyingKeyboard
// 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);
        }
    }
}

 

Unity 2D C# Drag And Drop GameObject Mouse Input
Tagged on:         

8 thoughts on “Unity 2D C# Drag And Drop GameObject Mouse Input

  • June 10, 2017 at 5:00 pm
    Permalink

    I can’t click my button when I use your script. Do you know why?

    Reply
    • June 10, 2017 at 7:12 pm
      Permalink

      Hey Steve, could you give me a little more detail about what you are trying to do, and how exactly does it not work?

      Reply
  • June 13, 2017 at 9:34 am
    Permalink

    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?

    Reply
    • June 13, 2017 at 6:57 pm
      Permalink

      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 🙂

      Reply
  • September 13, 2017 at 4:20 pm
    Permalink

    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

    Reply
    • September 13, 2017 at 4:32 pm
      Permalink

      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.

      Reply
      • September 13, 2017 at 7:03 pm
        Permalink

        Adjusting offset helped, I dont know why before with offset 0.01 nothing happened. It works fine. Thank You !!!

        Reply
        • September 14, 2017 at 7:14 am
          Permalink

          I’m glad to hear that 🙂

          Reply

Leave a Reply

Your email address will not be published. Required fields are marked *