- Home /
C# Script Multiple Prefabs, Same Transform
I have a prefab and I have put a few of them on the screen. I am not instantiating these at runtime I am instantiating them at design. I have created a script to make them move based on the mouse location once clicked on. For some reason when I click on one of the objects, the isGrabbed variable becomes true for all of them and they all move to the same location on top of each other. Can't seem to find the error here. Can anyone help out?
using UnityEngine; using System.Collections;
public class TestMove : MonoBehaviour {
public Vector3 mousePos = new Vector3(0,0,0);
public RaycastHit hit;
public bool isGrabbed;
public Vector3 newLocation = new Vector3(0,0,0);
public Vector3 initialPos = new Vector3(0,0,0);
public Ray ray;
public string name;
// Use this for initialization
void Start () {
transform.position =initialPos;
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButton(0))
{
mousePos = Camera.main.ScreenToWorldPoint( Input.mousePosition);
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
newLocation.x = mousePos.x;
newLocation.y = mousePos.y;
if (Physics.Raycast(ray, out hit))
{
isGrabbed = true;
transform.position = newLocation;
}
}
else
{
isGrabbed = false;
}
if (isGrabbed){
}
Debug.Log (name + transform.position);
}
}
The code formatting on this site is really maddening. Hardly anyone ever gets it right the first time. It's really starting to get on my nerves.
As for your problem. Why not use On$$anonymous$$ouseDown()? http://docs.unity3d.com/Documentation/ScriptReference/$$anonymous$$onoBehaviour.On$$anonymous$$ouseDown.html
On$$anonymous$$ouseDown sucks if you want to use more than 1 mouse button
At a glance it looks like you don't set isGrabbed to false when the raycast test fails.
Answer by Tomer-Barkan · Oct 28, 2013 at 09:14 PM
Your code does nothing to check if the object that was clicked is the current object (`this`), hence for each one of the objects that have the script, isGrabbed will be set true when the mouse is clicked.
Change your code this way:
if (Physics.Raycast(ray, out hit)) {
if (hit.collider = this.collider) { // check that the raycast actually hit THIS object
isGrabbed = true;
transform.position = newLocation;
}
}
Thanks. That was the issue. Its always something looking you in the face.