- Home /
Unity While Loop Freeze
I have a working while loop that moves objects around based on the amount of time a keypress would take to move it
Ex.
Forward(2.5);
//This would move the object forwards for 2.5 seconds
The thing is, Unity freezes for the time the function is running and starts rendering again when it has completed, or locks up and basically crashes.
Code:
void Forward(double time)
{
var t = time;
while(t >= 0)
{
GetComponent<Rigidbody>().position += (transform.forward * Time.deltaTime * movementSpeed);
t -= Time.deltaTime;
}
}
Keep in mind this loop works, but only half of the time, so the loop is proven to work
Answer by tanoshimi · Feb 06, 2017 at 10:52 PM
To make any operation span over several frames, you need to use [coroutines][1]. In your case, you'd change to the following:
IEnumerator Forward(double time)
{
var t = time;
while(t >= 0)
{
GetComponent<Rigidbody>().position += (transform.forward * Time.deltaTime * movementSpeed);
t -= Time.deltaTime;
yield return null;
}
}
and call the method using StartCoroutine()
[1]: https://docs.unity3d.com/Manual/Coroutines.html
Answer by Rs · Feb 06, 2017 at 11:10 PM
You really don't move things that way in Unity. You can use either coroutines as in tanoshimi's answer or, as you are using Unity's physics engine (by using a Rigidbody), put your code in the FixedUpdate function, which Unity calls at least once per frame. Something like:
void FixedUpdate()
{
GetComponent<Rigidbody>().position += (transform.forward * Time.deltaTime * movementSpeed);
}
If you enter a while loop like you are doing you are basically stopping the whole Unity engine to make its own loops.
Your answer
Follow this Question
Related Questions
Children's position going haywire (Unity bug?) 1 Answer
While Loop Issue 0 Answers
Quaternion Slerp Sanity Check 1 Answer
Quaternion.Slerp issue 1 Answer
Does Rigidbody.freezRotation allow transform.Rotate ? 1 Answer