Hey everyone,
I’m trying to make my first game, and the first puzzle is a very simple drag and drop one. However, every tutorial I’ve watched on how to make a drag and drop script doesn’t seem to work. It doesn’t even pop up with an error message or anything, I don’t think the puzzle piece is being recognized at all. I got chatGPT to write me a script with some debug messages as a last resort, but that script isn’t working either and when I hover over the puzzle piece, the mouse isn’t even detected.
Here are the links to the youtube videos I watched:
Here’s the script chatGPT gave me:
using UnityEngine;
public class DragAndDrop2D : MonoBehaviour
{
private Vector3 offset;
private float zCoord;
void OnMouseDown()
{
Debug.Log("Mouse DOWN on: " + gameObject.name);
// Store object's Z coordinate
zCoord = Camera.main.WorldToScreenPoint(transform.position).z;
// Calculate offset between object and mouse world pos
offset = transform.position - GetMouseWorldPos();
Debug.Log("Offset set to: " + offset);
}
void OnMouseDrag()
{
Debug.Log("Dragging: " + gameObject.name);
transform.position = GetMouseWorldPos() + offset;
Debug.Log("New position: " + transform.position);
}
void OnMouseUp()
{
Debug.Log("Mouse UP on: " + gameObject.name);
}
private Vector3 GetMouseWorldPos()
{
Vector3 mousePoint = Input.mousePosition;
// Maintain the object's Z so it doesn't jump
mousePoint.z = zCoord;
Vector3 world = Camera.main.ScreenToWorldPoint(mousePoint);
Debug.Log("Mouse world position: " + world);
return world;
}
}
Also, I opened a new project and quickly threw together a test to see if it was a problem with that specific project, however it still didn’t work.
I’m unsure if theres some hidden setting I need to configure or something, so any guidance would be greatly appreciated. If further info is needed, let me know. Thanks.