- Home /
Mouse-following script freezes Unity.
Hey there.
So i wanted to make a system where an object would be used to move a weapon around. For that i need the object to be in sync with the mouse movement , and the weapon will use that object as a pointer. So i got this code together:
#pragma strict
private var temp : Vector3;
function Update () {
while (Input.GetMouseButton(0))
{
temp = Input.mousePosition;
temp.z = gameObject.transform.position.z -Camera.main.transform.position.z;
transform.position = Camera.main.ScreenToWorldPoint(temp.normalized);
}
}
I can see that it more or less works , as the objects coordinates are changing in synch with cursor movement, BUT!
1: If i removed the `while (Input.GetMouseButton(0))` , the object just... disappeared. it still must be in visible coordinates range ,so i have no idea what whichcraft is going on here, but moving the cursor does make the coordinates shift.
2: When i leave `while (Input.GetMouseButton(0))` in , upon pressing the LMB Unity freezes, it just locks up.
I am really kind of baffled about whats going on here ,so any help would be greatly appriciated.
Thanks!
EDIT: Thanks to ThermalFusion, the freeze problem was solved. But our job does not end there, as now a new problem emerged. Now i could see that the box was just warped to the cameras z coordinate for some reason, even though that the line
temp.z = gameObject.transform.position.z -Camera.main.transform.position.z;
should have fixed that. I added +60 to the end of that line ,so i could see some results ,and the x and y coordinates sync up perfectly, whereas the object seems to be going on an ellipsoid-shaped round around me. where it is only like 20 units sfrom me on one side ,and at the opposite ,its like +30000000 or something. We still need to find the witch.
Answer by ThermalFusion · Sep 13, 2012 at 10:36 PM
Try using temp instead of temp.normalized:
transform.position = Camera.main.ScreenToWorldPoint(temp);
while loops the code inside the curly brackets until its conditions are no longer true as Input.GetMouseButton(0) never gets set to false inside there, it will keep looping forever and Unity will crash. You want to use if here instead:
if (Input.GetMouseButton(0))
Then it will only do the code once. And because it is inside the Update function, it will do what's inside Update once every frame.
temp.z = gameObject.transform.position.z -Camera.main.transform.position.z;
temp.z = 25f; // use this instead
You should probably change the line above to the exact distance from the camera you want the object to be placed.
Thank you ,thats one obsticle down! But a new one needs tackling.