while(Input.GetMouseButton(0))
{
MovetoCursor();
}
Yeah, that’s an infinite loop apparently. whoops. I had to ctrl-alt-del unity and it snurgled up my previously imported assets. Just don’t.
while(Input.GetMouseButton(0))
{
MovetoCursor();
}
Yeah, that’s an infinite loop apparently. whoops. I had to ctrl-alt-del unity and it snurgled up my previously imported assets. Just don’t.
Hi,
You are supposed to be in a “if” statement, not a “while”.
M. D.
Sorry to hear that and I hope everything is working fine now.
I don’t know if this is the right place to ask this question, but is this technically an infinite loop? Somebody please double check me on this, but I suspect that what’s actually happening is that when you click and hold the mouse button down there is a very large amount of calls to MovetoCursor() being put on the call stack. I don’t know if that’s exactly right, but my computer science brain is very curious about the technical details here
The problem is that a while loop outside of a coroutine is always a blocking operation…
The condition is evaluated, and the left mouse button is found to be down
The while loop, in the meantime never releases it’s time slice, it keeps calling MoveToCursor(), and when the call returns, control still hasn’t been returned to the main thread (remember that Unity is a single threaded program!). MoveToCursor evaluates the button state, but since it never released control back to the main thread, the input system was never able to reset GetMouseButton(), so it calls MoveToCursor() again… and again… and… well you get the idea.
While loops work well in coroutines, because they are written in a way to operate in time slices…
IEnumerator PollCharacterMovement()
{
while(Input.GetMouseButton(0))
{
MoveToCursor();
yield return null; //This lets the game continue to the next frame
}
}
Of course, this is a horrible example, because the game simply doesn’t work this way, but I put it there just to explain what’s happening behind the scenes.
Thank you for this explanation! This makes a lot of sense now. I didn’t know that Unity is a single threaded program. I think I assumed it had to be multithreaded in order to make coroutines work, but as it turns out that isn’t true. With that context, I see why this is an infinite loop. Thanks again for explaining about what’s happening under the hood.
While there is multithreading available if you use the Entity Component System (DOTS), Unity is indeed single threaded. Even a coroutine will block and freeze and app if it doesn’t yield return
pretty regularly (like, less than an average Update loop takes). The system runs all the updates, then runs all the Coroutines, then draws the screen and runs back to do it all over again. (It’s actually more complex than that, but for our purposes, that about covers it)