- Home /
beginner coder question, is this code right?
var speed:float; function Update () { if(Input.GetKey(KeyCode.D)){ while(transform.position.x>-5.5 && transform.position.x<5.5){
transform.Translate(Vector3(1*Time.deltaTime*speed,0,0));
} }
}
I type this into unity and when I pres play and press D, the program just freezes.. I'm guessing that I'm making a beginner mistake or something..Anyone care to help/explain?
The program is freezing most like because the logic in your while loop may be wrong, but it is kind of hard to tell what this code is doing.... what is the code suppose to be doing?
Answer by Thom Denick · Nov 02, 2010 at 01:57 AM
It's probably freezing because it's stuck in the While Loop, Whiles are tricky in Unity, because they cause it to freeze - if you can, try using an If in your Update() method.
It's hard to say what exactly is wrong here if this compiles correctly. You can effectively debug your code to see what's going on by using the Debug.Log class.
You can also create an escape for the while loop by creating a bool that gets triggered true when your object is where you want it - or - you have cycled your while enough times.
Actually - it's probably because your speed is set to 0. Are you setting it on the object in Unity?
well, thanks. But I was doing it all wrong lol, I don't know what made me use "while" rather than "if" hehe. sorry, I'm new to coding :\
Your answer
Follow this Question
Related Questions
Unity Crashes From While Loop and Can't fix 0 Answers
Do-while loop freezes the engine when running the game -1 Answers
What is wrong in my code - Unity freezes 1 Answer
Rigidbody.Freezerotation doesn't work properly? 0 Answers
Unity Crashes From While Command 7 Answers