Why is this While loop causing infinite compile times?

I am trying to make this variable = to my gameClock/5 (i.e. every 5 seconds it’s value is 1 higher).

public class LogicScript : MonoBehaviour
{
    public int playerScore;
    public Text Score;
    public float gameClock;
    public TMP_Text GameClock;
    public int pipeSpeedModifier = 0;
    public int maxPipeSpeedModifier = 10;


    public void Update()
    {
        
            while (pipeSpeedModifier < maxPipeSpeedModifier)
        {
            pipeSpeedModifier = Mathf.FloorToInt(gameClock/5);
            Debug.Log($"pipeSpeedModifier: = {pipeSpeedModifier}");
        }

        gameClock += Time.deltaTime;
        //Debug.Log($"gameClock = {gameClock.ToString()}");

        int minutes = Mathf.FloorToInt(gameClock / 60F);
        int seconds = Mathf.FloorToInt(gameClock - minutes * 60);

        GameClock.text = string.Format("{0:0}:{1:00}", minutes, seconds);
    }

It was working fine until I reset the value in the inspector to make it higher. I suppose it wasn’t using the while loop until I did that since 0 is NOT < 0. So what exactly is happening here to make it load infinitely?

Before I set a variable to define maxPipeSpeedModifier, the pipeSpeedModifier variable would increment as intended - it just got to the point where my game was unfun and impossible so I wanted to set a cap on the incrementation.

If it enters that loop gameclock never changes. So the result will remain and likely it infinite loops.

I

1 Like

in your while loop, there is nothing that could increase pipeSpeedModifier iteratively, so when gameClock is too low, pipeSpeedModifier is always lower than maxPipeSpeedModifier

not sure what it should do

1 Like

So I am new to programming. I assumed this worked like an if statement, with the code unside the loop executing once each frame until a condition was met. Thanks for helping with my dumb question!

No while is exactly that

while jug is not full add water; … add water, add water, add water… ooh jug filled - what next boss?

an if statement could be the right answer, but as a programmer it is down to you to commadn your code to be the design you made :slight_smile:

Worth pointing out that C# is not specific to only Unity, and there’s ample information on these core language concepts available on the net.

1 Like