While loop crashes Unity

Hello.
I have come across a little bug which I haven’t found the explanation. Whenever I try to load a specific code with a while loop, when I click play Unity crashes and gets stuck forever. Sometimes it even crashes my computer. Here is the code:

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

public class test : MonoBehaviour
{

    int targetInt = 0;
    
    void Start()
    {
       
    }

    // Update is called once per frame
    void Update()
    {
        while(targetInt < 30)
        {
            Invoke("Increase", 1f);
        }
        //This is the loop that crashes everything
        Debug.Log(targetInt);
    }

    void Increase()
    {
        targetInt++;
    }
   
}

I have seen a thread that said that if Unity encounters an infinite loop, it will crash and not function, but I feel that this isn’t an infinite loop, unless I used Invoke incorrectly. Thanks.

Unity will lock up 100% of the time EVERY millisecond your scripting code is running.

Nothing will render, no input will be processed, no Debug.Log() will come out, no GameObjects or transforms will appear to update.

Absolutely NOTHING will happen… until your code either:

  • returns from whatever function it is running

  • yields from whatever coroutine it is running

As long as your code is looping, Unity isn’t going to do even a single frame of change. Nothing.

No exceptions.

“Yield early, yield often, yield like your game depends on it… it does!” - Kurt Dekker

1 Like

This is almost a textbook example of an infinite loop, and I’m not really sure how you could think it wouldn’t be one? Invoke runs your code “later”. “later” will never happen because we’re stuck inside this infinite loop and your Update function never ends.

2 Likes

You haven’t unfortunately. Unity needs to proceed through it’s player loop (ergo, the loop that calls Update, FixedUpdate, etc) for timed stuff to work. Currently your code enters the loop, invokes a method to be called in 1 second, and then… continues on looping, doing this same thing forever. The player loop never proceeds and thus Unity remains forever locked up.

This is a situation where you want to look into coroutines.

1 Like

Pretty sure an infinite loop is basically Unity or any other program saying……yeah I’m crashing

1 Like