Game freezes on play

When I apply the following script to a game object, it freezes Unity as soon as I click play and does so without showing any errors. I am forced to use task manager to exit Unity. 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Fly : MonoBehaviour {

public float speed = 50f;
public int time = 1;

void Start()
{

}

void Update()
{
while (time > 0)
{
transform.Translate(Vector3.forward * speed * Time.deltaTime);
}


}
}

If I remove the while statement and only leave the transform, the game plays without a problem.

Does anyone have any idea on what could be wrong? Thanks!


  • Bartosz Piłat(krajca) replied

    It's quit simple - you have infinity while loop

    while (time > 0)
    {
    transform.Translate(Vector3.forward * speed * Time.deltaTime);
    }

    time is set to 1 ant the beginning and never change so it's always greater than 0
    to fix this you need to change that value i.e.:

    while (time > 0)
    {
    transform.Translate(Vector3.forward * speed * Time.deltaTime);
    time -= Time.deltaTime
    }

  • Jonathan Gonzalez(jgonzalez) replied

    Yep, the while loop is causing the issue as pointed above. While loops are typically used for specific time frames or conditions. Is there a reason why you're using a while loop to move an object? It looks like you want this object to move forward while the game is playing, in that case you wouldn't need a while loop since it will never stop in which case you could put it in Update or a separate method. If you wanted it to move forward over a given time then you'd need to have some sort of time value to determine when it will stop.