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

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]: Unity - Manual: Coroutines

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.