- Home /
Drag-and-drop problem
Hi. I have a problem about Drag-and-drop object. Below is my script attached to my object. I want player must click on Object to move it but now they can click anywhere on screen and then move the object. And the second problem is, if I have 2 objects, if I move an object, the rest also move with first object.
using UnityEngine;
using System.Collections;
public class DragDrop2 : MonoBehaviour {
private Vector3 screenPoint;
private Vector3 offset;
void Update(){
if (Input.GetButtonDown ("Fire1")) {
screenPoint = Camera.main.WorldToScreenPoint (transform.position);
offset = transform.position - Camera.main.ScreenToWorldPoint (new Vector3 (Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
Screen.showCursor = false;
}
if (Input.GetButton ("Fire1")) {
Vector3 curScreenPoint = new Vector3 (Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
Vector3 curPosition = Camera.main.ScreenToWorldPoint (curScreenPoint) + offset;
transform.position = curPosition;
}
if (Input.GetButtonUp ("Fire1")) {
Screen.showCursor=true;
}
}
}
$$anonymous$$ove all your logic from Update() to On$$anonymous$$ouseDown() and On$$anonymous$$ouseDrag().
@robertbu but On$$anonymous$$ouseDown() and On$$anonymous$$ouseDrag() don't work with Touch
1) On$$anonymous$$ouseDown() and On$$anonymous$$ouseDrag() do work with touch, 2) your existing code does not work with touch, and 3) and nothing in your questions indicates you are working on a touch solution.
@robertbu yes, I will try to replace my On$$anonymous$$ouseDown() and On$$anonymous$$ouseDrag() to see if it work. Thank you :D
Your answer
![](https://koobas.hobune.stream/wayback/20220613150819im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
snap to point remove 0 Answers
How to drag Unity Objects to other c# application 0 Answers
DragAndDrop class bugged? 1 Answer
Drag 2dtexture from inventory to game. 0 Answers
Dragrigidbody help 1 Answer