- Home /
Unity Crash on Function Run
Hello, can any tell me why this causes unity to crash (before I even get an error msg.)
var pressed : int;
function Update () {
if (Input.GetMouseButtonDown(0)){
pressed = 1;
mouseCheck();
}
}
function mouseCheck () {
while (pressed==1){
if (Input.GetMouseButtonUp(0)){
pressed=0;
}
}
}
-- I've tried commenting out different lines and "while (pressed==1)" seems to be the problem, any input as to why this is happening?
Cheers
Yes -- you set pressed to 1 and then it goes into a loop until the Get$$anonymous$$ouseButtonUp(0) returns true, which most likely won't happen because you killed the CPU already.
Answer by Gareth Rees · Nov 11, 2010 at 10:02 PM
As the others have said, your function mouseCheck
loops forever: it keeps checking to see if the mouse button is up, without letting any other code get a look in, and that includes the code for updating the mouse button status. (So even if you release the mouse button, your code never gets to find out.)
So I suggest making mouseCheck
into a coroutine that calls yield
to give other code a chance to run:
var pressed = false;
function Update () { if (Input.GetMouseButtonDown(0)) { pressed = true; mouseCheck(); } }
function mouseCheck () { while (pressed) { yield; if (Input.GetMouseButtonUp(0)) { pressed = false; } } }
Answer by matyicsapo · Nov 11, 2010 at 09:29 PM
infinite loop, the if in mouseCheck checks the value in the same frame halting program execution
look into Coroutines, Events(OnMouseXXX methods especially), or just put the 2nd if into Update checking for MButtonUp every frame