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.
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.
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.