I want to create drag and drop functionality for a gameObject. When user touches the object it creates a duplicate and the duplicate supports drag and drop features when the original object remains in its position. When I apply it only on the original gameobject without creating duplicate it works fine but when I create the duplicate, both original object and duplicate start to translate automatically through y-axis. I cannot find the solution. please help out.
Here is my script for the gameObject:
using UnityEngine;
using System.Collections;
public class DragableBrick : MonoBehaviour
{
bool isDragable = false;
public GameObject replica;
// Use this for initialization
void Start ()
{
if (this.name != "Brick") {
isDragable = true;
}
}
// Update is called once per frame
void Update ()
{
}
void OnMouseDown(){
if(isDragable == false){
if(replica != null){
Instantiate(gameObject, this.transform.position, Quaternion.identity);
}
}
}
void OnMouseDrag(){
if(isDragable == true){
this.gameObject.transform.Translate (Event.current.delta.x * Time.deltaTime, -Event.current.delta.y * Time.deltaTime, 0);
}
}
}
You have a ways to travel to get this code working correctly. Plus I’m not sure the behavior you are seeing is what you are describing (or at least the code above does not produce the behavior).
The really big issue is line 27. ‘Event’ is an GUI communication and is not valid outside of OnGUI. Even if it was, the values would be in GUI coordinates, not world coordinates.
Here is a script that is an approach to your problem. It assumes the camera is looking at positive ‘Z’. The easiest way to test it is to create a new scene and then place the script on a cube.
Note because of the way OnMouseDrag() works, what gets dragged is the original object, not the clone. But since they should be identical in everything but name (and that could easily be ‘fixed’), hopefully this should not be a problem.