- Home /
While Statement Causing Unity to Crash,While Statement Freezing Unity
void Update() { horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed; while (Input.GetKeyDown("d")) { Debug.Log("d"); move = GetComponent(); move.velocity = velocity; velocity = Vector2.zero; GetComponent().velocity = new Vector3(3, 0, 0)
}
while (Input.GetKeyDown("a"))
{
GetComponent<Rigidbody2D>().velocity = new Vector3(-3, 0, 0);
}
}
Not sure why this code is crashing unity, I know its because it turns into a infinite loop but im not sure whats causing it
,I am trying to make it so when I hold down the key the player continues moving, right now the player just moves a little. When using a while statement it freezes. https://prnt.sc/V0hYE_gQaVz_
Answer by rh_galaxy · Apr 06 at 01:59 AM
Why would you want to do a while-loop to set a value to velocity?
The loop will never end because if Input.GetKeyDown("a") is true at one time it will never become false, since no other code will run during the loop. You have to let Update() exit to let Input.GetKeyDown() be updated and then check it again in the next Update(). But if you want to check if the key is pressed you should use Input.GetKey() instead.
Use:
if(Input.GetKeyDown("a"))
{
//...
}
Your answer
Follow this Question
Related Questions
How can I get Unity to work on win7? 4 Answers
How do I freeze a rigidbody2d using script? 2 Answers
Game freezes on Google Play Store 0 Answers
Do-while loop freezes the engine when running the game -1 Answers
Native debugging 0 Answers