unity script for dragable object in csharp

To create a draggable object in Unity using C#, you can attach a script to the GameObject of the object you would like to drag. Here is an example script that allows you to drag an object using mouse input:

main.cs
using UnityEngine;

public class Draggable : MonoBehaviour
{
    private bool isDragging = false;
    private Vector3 offset;

    private void OnMouseDown()
    {
        offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10.0f));
        isDragging = true;
    }

    private void OnMouseUp()
    {
        isDragging = false;
    }

    private void Update()
    {
        if (isDragging)
        {
            Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10.0f);
            Vector3 objPos = Camera.main.ScreenToWorldPoint(mousePos) + offset;
            transform.position = objPos;
        }
    }
}
717 chars
29 lines

The OnMouseDown function is called when the mouse button is pressed down on the object. It calculates the difference between the object's position and the position of the mouse click, and sets isDragging to true.

The OnMouseUp function is called when the mouse button is released. It sets isDragging to false.

The Update function is called once per frame, and checks whether isDragging is true. If it is, it gets the current mouse position, converts it to world coordinates, and adds the offset calculated in OnMouseDown. Finally, it sets the object's position to the new position.

To use this script, attach it to the GameObject of the object you would like to drag. When you run the game, you should be able to click and drag the object using the mouse.

gistlibby LogSnag