Problem with drag and drop

private var ray:Ray;
private var hit:RaycastHit;
function Start () {

}

function Update () {
if(Input.GetMouseButton(0)){
ray=Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray,hit)){
transform.position.x=hit.point.x;
transform.position.y=hit.point.y;
}
}

}

so i was using this script to do a drag and drop and it worked fine, but when i have multiple objects with this script attached to them once i drag one all the others move with how can i edit this script so that i drag only the one i want to drag
thanks

why use of hit.transform.name == transform.name

1 Answer

1

Please properly format your code in the future, so it’s readable. As to your issue, you’re not checking what is being hit, so if you just hit anything you will move any objects that have this script. Do something like this:

if(Physics.Raycast(ray,hit)){
	if (hit.transform.name == transform.name) {
		transform.position.x=hit.point.x;
		transform.position.y=hit.point.y;
	}
}

why use of hit.transform.name==transform.name

To make sure the raycast hits THIS object where this script is attached to. Checking for the objects name is one example u can check for hit.transform.gameObject too.

if i use a object with extension ".obj" and i want to use hit.transform.name why not do the same that other